Fundamentals of Data Structures for Algorithmic Learning
Arithmetic Operations on Numbers
Basic operations include addition (+), subtraction (-), multiplication (*), and division (/). Use floor division (//) for integer results (rounds down). Modulo (%) returns the remainder. Functions: abs(x) for absolute value, max(x, y)/min(x, y) for extrema, pow(x, y) for exponentiation ($x^y$), and math.sqrt(x) for square roots (requires import math).
Lists
Ordered colections declared with square brackets, supporting mixed data types (e.g., my_list = [2, 3.14, "data"]).
Core Operations
- Access: Indexing starts at 0 (e.g.,
my_list[0]retrieves 2). - Append:
my_list.append(5)adds elements to the end. - Udpate: Reassign via index (e.g.,
my_list[1] = 2.71). - Delete:
my_list.pop()removes the last element;my_list.pop(0)removes the first.
Utility Functions
- Length:
len(my_list) - Extrema:
max(my_list),min(my_list) - Reverse:
my_list.reverse() - Clear:
my_list.clear()(results in[]) - Initialize:
zeros = [0] * len(my_list) - Membesrhip:
3 in my_list(returns boolean) - Slice: Extract sublists with
my_list[start:end](left-closed, right-open). Negative indices count from the end (e.g.,my_list[:-1]excludes the last element).
Iteration
# By element
for item in my_list:
print(item)
# By index
for idx in range(len(my_list)):
print(my_list[idx])
List Comprehensions
Generate lists concisely:
# Square elements
squares = [x**2 for x in my_list]
# Conditional transformation
modified = [x**3 if x > 2 else x for x in my_list]
Tuples
Immutable ordered collections declared with parentheses. Single-element tuples require a trailing comma (e.g., single = (42,)). Supports indexing, slicing, and membership checks like lists. Convert between lists and tuples with tuple(my_list) and list(my_tuple).
Sets
Unordered collectinos of unique elements declared with curly braces (e.g., my_set = {1, 2.5, "algo"}).
Operations
- Add:
my_set.add(3)(ignores duplicates);my_set.update([4, 5])adds multiple elements (supports iterables like lists/tuples). - Remove:
my_set.remove(2)(raises error if missing);my_set.pop()removes an arbitrary element. - Membership:
"algo" in my_set
Set Logic
- Union:
a | b(elements in either) - Intersection:
a & b(elements in both) - Difference:
a - b(elements inanot inb) - Symmetric difference:
a ^ b(elements in exactly one set)
Dictionaries
Key-value pairs declared with curly braces (e.g., my_dict = {"topic": "DS", "level": "basic"}). Keys are unique and used for access.
Operations
- Access:
my_dict["topic"]→"DS" - Add/Update:
my_dict["author"] = "engineer" - Delete:
my_dict.pop("level")
Iteration
# Keys
for key in my_dict:
print(key)
# Values
for val in my_dict.values():
print(val)
# Key-value pairs
for k, v in my_dict.items():
print(f"{k}: {v}")
Strings
Immutable sequences of characters (e.g., my_str = "hello world").
Common Methods
- Length:
len(my_str)(includes spaces) - Extrema:
max(my_str)/min(my_str)(by ASCII value) - Count:
my_str.count("l")→ 3 - Case checks:
isupper(),islower(),isdigit(),isalpha() - Transformations:
lower(),upper(),swapcase() - Trimming:
strip()(both ends),lstrip()(left),rstrip()(right) - Replace:
my_str.replace("world", "universe") - Split:
my_str.split(" ")→["hello", "world"]
Arrays
Homogeneous lists (all elements same type) stored in contiguous memory. Fast indexed access; slow insertion/deletion due to reallocation.
Linked Lists
Nodes containing a value and a pointer to the next node. Non-contiguous storage enables fast insertion/deletion (pointer updates); slow random access.
Hash Tables
Key-value stores using hash functions to map keys to memory locations. Combines dictionary-like O(1) lookups with linked-list-like efficient insertions/deletions. No direct indexing support.
Queues
First-In-First-Out (FIFO) structures. Implement with lists (inefficient pop(0)) or collections.deque:
from collections import deque
q = deque()
q.append(1) # Add right
q.appendleft(2) # Add left
q.pop() # Remove right
q.popleft() # Remove left
Stacks
Last-In-First-Out (LIFO) structures. Use deque with append()/pop() (right-side) or appendleft()/popleft() (left-side).
Heaps
Binary trees with heap property (min-heap: parent ≤ children; max-heap: parent ≥ children). Default is min-heap. Use heapq module:
import heapq
heap = [3, 1, 4]
heapq.heapify(heap) # Convert list to heap
heapq.heappush(heap, 2) # Add element
heapq.heappop(heap) # Remove smallest
heapq.nlargest(2, heap) # Top 2 largest
heapq.nsmallest(2, heap) # Top 2 smallest
For max-heap, store negated values.
Trees
Heirarchical structures with nodes (root, leaves, siblings). Key metrics: height (longest path from root to leaf), depth (path from root to node), level (depth + 1).
Binary Tree Types
- General: Nodes have 0–2 children.
- Full: All non-leaf nodes have 2 children.
- Complete: Nodes filled left-to-right at each level (like a heap). Traversal methods include pre-order, in-order, post-order.