What does Big-O notation describe?
Growth rate of an algorithm as input size n → ∞. Drop constants and lower-order terms. Ordering: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n) < O(n!).
DSA · 14 sections
Arrays, linked lists, stacks, queues, hash maps, trees, graphs — and the Big-O that decides between them.
Growth rate of an algorithm as input size n → ∞. Drop constants and lower-order terms. Ordering: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n) < O(n!).
Big-O is an upper bound, Big-Omega a lower bound, Big-Theta a tight bound (both). Use Θ when upper and lower match; interviewers usually mean O.
Average cost per operation over a worst-case sequence. Dynamic array append is O(1) amortized despite occasional O(n) resize; union-find is near O(1) amortized.
Hash map uses O(n) space for O(1) lookup; memoization trades space for time; in-place sorting saves space. Choose based on constraints.
Quicksort is O(n log n) average but O(n²) worst; hash map O(1) average but O(n) worst. Always clarify which case.
Master theorem: for T(n)=aT(n/b)+f(n), compare f(n) with n^(log_b a). Here a=b=2 so n^(log_b a)=n=f(n) → Θ(n log n) (merge sort). Cases: smaller f → Θ(n^(log_b a)); equal up to a log factor → Θ(n^(log_b a) log^(k+1) n); polynomially larger f satisfying regularity → Θ(f(n)).
# T(n) = 2T(n/2) + O(n) → a=2, b=2, f(n)=n
# n^(log_b a) = n == f(n) → case 2 → O(n log n)
For small n or tight constraints, an O(n) algorithm with a large constant can lose to O(n log n) with a small one. Measure, don't assume.
String concatenation in loops, boxing primitives, cache misses, and recursion overhead. Big-O ignores constants but hardware does not.
Auxiliary space excludes input. In-place sorts use O(1) auxiliary; merge sort uses O(n). Report auxiliary unless asked otherwise.
Contiguous memory block. O(1) random access, O(n) insert/delete (shifting), excellent cache locality. Fixed size in many languages.
Amortized O(1). Overallocate capacity; when full, allocate ~2× and copy. Occasional O(n) resize averaged over many appends.
With constant growth (say +10 slots) every append eventually copies all elements: O(n) amortized per append, O(n²) total for n appends. Geometric growth copies 1+2+4+… ≈ 2n total, so amortized O(1) per append.
Contiguous elements fit cache lines; sequential access is fast. Linked lists scatter nodes, causing cache misses.
Iterate in storage order for cache. Row-major: iterate rows outer. Column-major (Fortran): iterate columns outer. Mismatch can be 10× slower.
Two pointers (fast/slow): slow marks the write position; copy a[fast] when different. O(n) time, O(1) space. Empty input returns 0.
if n == 0: return 0
slow = 0
for fast in range(1, n):
if a[fast] != a[slow]:
slow += 1; a[slow] = a[fast]
return slow + 1
pre[i]=sum of first i elements. Range sum [l,r] = pre[r+1]-pre[l] in O(1) after O(n) preprocessing.
pre = [0]*(n+1)
for i in range(n): pre[i+1] = pre[i] + a[i]
# range sum [l,r] (0-based inclusive):
range_sum = pre[r+1] - pre[l]
For range add [l,r] += v: diff[l]+=v, diff[r+1]-=v. Reconstruct with prefix sum in O(n). O(1) per update.
diff = [0]*(n+2)
def range_add(l, r, v): diff[l]+=v; diff[r+1]-=v
# reconstruct:
cur=0
for i in range(n): cur+=diff[i]; a[i]=cur
Store only non-zero entries as (index,value) pairs or a hash map. Saves space when density is low.
Length n means valid indices 0..n-1. Prefer half-open intervals [l, r) to avoid fencepost errors.
int[] is fixed and stores primitives (no boxing). ArrayList<Integer> is dynamic but boxes ints, adding overhead and nullability.
Almost always for read-heavy or cache-sensitive workloads: contiguous memory wins on prefetching and constant factors. Linked lists win for O(1) splice at a known node with no traversal, and when you need stable references/iterators that stay valid across inserts and deletes (LRU lists, intrusive lists, lock-free structures where nodes are swapped atomically rather than moved).
Node has next pointer. O(1) insert/delete after a known node, O(n) access/search by index. Head insert O(1).
prev and next pointers. O(1) delete a given node (no predecessor search). Costs extra memory per node.
Tail.next points to head. Used in round-robin scheduling and Josephus problems. Careful to avoid infinite loops.
Track prev/curr/next: next=curr.next; curr.next=prev; prev=curr; curr=next. O(n) time, O(1) space.
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
Recurse to end, then relink on unwind. O(n) time but O(n) stack space.
Slow pointer moves 1 step, fast 2. If they meet, there's a cycle. To find entry: reset one pointer to head, advance both by 1; meeting point is entry.
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow = slow.next; fast = fast.next
return slow
return None
Fast/slow pointers: when fast reaches end, slow is at middle. Handles even length by convention.
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
Dummy head; repeatedly attach smaller current node; O(n+m) time, O(1) extra (relinking).
dummy = ListNode(0); t = dummy
while a and b:
if a.val <= b.val: t.next = a; a = a.next
else: t.next = b; b = b.next
t = t.next
t.next = a or b
return dummy.next
Two pointers with gap n: advance fast n steps, then move both; when fast reaches end, slow.next is target.
dummy = ListNode(0, head); slow = fast = dummy
for _ in range(n): fast = fast.next
while fast.next:
slow = slow.next; fast = fast.next
slow.next = slow.next.next
return dummy.next
Align lengths: compute both lengths, advance longer by difference, then walk together. Or two-pointer swap trick.
Each node stores pointer(s) plus allocation metadata; poor cache locality. For large datasets, arrays often faster despite O(n) shifts.
Hash map (key → node) plus doubly linked list: the map gives O(1) lookup, the list gives O(1) move-to-front and O(1) evict from the tail. Both get and put are O(1). OrderedDict implements the pair for you; in an interview be ready to hand-roll a dict plus prev/next pointers.
from collections import OrderedDict
class LRUCache:
def __init__(self, cap):
self.cap = cap; self.d = OrderedDict()
def get(self, k):
if k not in self.d: return -1
self.d.move_to_end(k) # mark as recently used
return self.d[k]
def put(self, k, v):
self.d[k] = v
self.d.move_to_end(k)
if len(self.d) > self.cap:
self.d.popitem(last=False) # evict least recently used
push/pop/top O(1). Uses: function call frames, undo/redo, DFS, expression parsing, monotonic stack problems.
st = []
st.append(x) # push
st[-1] # peek
st.pop() # pop
enqueue/dequeue O(1). Uses: BFS, scheduling, buffering, sliding window. Use collections.deque — list.pop(0) is O(n).
from collections import deque
q = deque()
q.append(x) # enqueue
q.popleft() # dequeue
Double-ended queue: push/pop both ends O(1). Used for sliding window max/min and 0-1 BFS.
Heap-backed: insert and extract-min/max O(log n), peek O(1). Used for Dijkstra, task scheduling, top-K.
Stack maintaining increasing or decreasing order; pop while order violated. Each element pushed/popped once → O(n). Next greater element, histogram area.
stack=[]
for x in a:
while stack and stack[-1] < x: stack.pop()
stack.append(x)
Deque stores indices in decreasing (max) or increasing (min) value order; pop the back while the new element dominates, pop the front when it leaves the window. O(n) total.
from collections import deque
def window_max(a, k):
dq, out = deque(), []
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x: dq.pop() # keep decreasing
dq.append(i)
if dq[0] <= i - k: dq.popleft() # out of window
if i >= k - 1: out.append(a[dq[0]])
return out
Enqueue pushes to in-stack; dequeue pops from out-stack, refilling from in-stack when empty. Each element moves at most once → amortized O(1) per operation.
inb, out = [], []
def push(x): inb.append(x)
def pop():
if not out:
while inb: out.append(inb.pop())
return out.pop()
def peek():
return out[-1] if out else inb[0]
Parallel stack of minimums, or store (value, currentMin) pairs. O(1) min without extra scan.
stack, mins = [], []
def push(x):
stack.append(x)
mins.append(x if not mins else min(x, mins[-1]))
def pop():
mins.pop(); return stack.pop()
def get_min(): return mins[-1]
Push opens; on close, pop and match. Empty stack at the end and no mismatch → valid. O(n) time, O(n) space.
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
Convert infix to postfix with an operator stack (respect precedence), then evaluate RPN with a value stack.
Recursion uses the call stack; deep recursion risks stack overflow. Convert to iterative with explicit stack when depth is large.
Array-backed has better cache and simpler code; linked is unbounded but slower. Prefer a circular buffer for queues.
Hash function maps key to bucket index; store value there. Average O(1) lookup/insert/delete. Worst case O(n) if all keys collide.
Chaining: linked list per bucket (simple, handles high load). Open addressing: probe for empty slot (better cache, needs tombstones on delete).
α = n/m. Resize (rehash) when α exceeds threshold (≈0.75). Doubling capacity keeps amortized O(1) insert.
Deterministic, fast, uniform distribution, avalanche (small input change → large output change).
If a key mutates after insertion, its hash/bucket changes and lookup fails. Python requires hashable (usually immutable) keys.
Linear: check next slots (clusters). Quadratic: jump by square (less clustering). Double hashing uses a second hash for step size.
Use randomized/universal hashing to defeat adversarial inputs; some langs (Java) treeify buckets (O(log n)) when chains grow.
Set stores keys only (membership O(1)); map stores key→value. Set is a map with dummy values.
Distribute keys across nodes so adding or removing a node moves only about a 1/n fraction of them — O(K/n) keys out of K, not all of them. Nodes and keys sit on a hash ring; virtual nodes smooth the distribution. Used in distributed caches and sharding.
For a static set, two-level hashing gives O(1) worst-case lookup with O(n) space.
On collision, steal from the richer (longer-probed) entry to balance probe lengths; lowers variance and max probe.
Hash table O(1) avg but unordered and worst O(n); BST O(log n) guaranteed and ordered. Need ordering/range queries → BST.
Binary tree: each node ≤2 children, no ordering. BST: left < root < right, enabling O(log n) search when balanced.
O(h): O(log n) if balanced, O(n) if skewed (e.g., sorted insertion). Self-balancing trees fix this.
def insert(node, val):
if node is None: return Node(val)
if val < node.val: node.left = insert(node.left, val)
elif val > node.val: node.right = insert(node.right, val)
return node # duplicates ignored
Balance factor (height diff) ∈ {-1,0,1}; rotations on insert/delete. Stricter balance → faster search, more rotations.
Nodes colored red/black with constraints; O(log n) guaranteed. Looser than AVL → fewer rotations, faster updates. Used in std::map/TreeMap.
AVL: faster lookup, more rebalancing. RB: faster insert/delete, slightly slower search. Both O(log n).
Inorder (left, root, right) yields sorted order for BST; preorder (root first) for serialization; postorder (children first) for deletion; level-order via queue.
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)
return out
Deepest node that is ancestor of both. Binary lifting allows O(log n) queries after O(n log n) preprocess.
Longest path between any two nodes. Compute via DFS returning height; diameter = max(leftH + rightH) across nodes. O(n).
Preorder with null markers (e.g., '1,2,null,null,3') uniquely reconstructs a binary tree. O(n).
Binary tree over array intervals; range query and point/range update in O(log n); build O(n). Use for sum/min/max/gcd.
def build(node,l,r):
if l==r: tree[node]=a[l]; return
m=(l+r)//2
build(2*node,l,m); build(2*node+1,m+1,r)
tree[node]=tree[2*node]+tree[2*node+1]
Array-based; prefix sums and point updates in O(log n). Simpler and faster constant than segment tree; range updates need difference BIT.
def update(i,delta):
i+=1
while i<=n: bit[i]+=delta; i+=i&-i
def query(i): # prefix sum [0..i]
s=0; i+=1
while i>0: s+=bit[i]; i-=i&-i
return s
Complete binary tree: min-heap parent ≤ children (root is min); max-heap parent ≥ children. Shape property ensures O(log n) height.
Index i: parent (i-1)/2, children 2i+1 and 2i+2. No pointers; cache-friendly.
Bottom-up heapify is O(n), not O(n log n). Top-down insertion of n elements is O(n log n).
Insert: append then sift up O(log n). Extract: swap root with last, remove, sift down O(log n). Peek O(1).
Heap gives O(1) peek and O(log n) insert/extract but no search/order; BST gives O(log n) search and ordered traversal. Different use cases.
Binary heap is standard. Need decrease-key (Dijkstra) → indexed heap or Fibonacci heap for better amortized bounds; in Python, push duplicates and skip stale pops instead.
Min-heap of size K while scanning: O(n log K). For K small, better than sorting O(n log n).
Max-heap for the lower half, min-heap for the upper half, sizes differing by at most 1. With an odd count the median is the top of the larger heap; with an even count it is the average of both tops. O(log n) per insert, O(1) median.
Build max-heap O(n), then repeatedly extract max to end. O(n log n) time, O(1) space, unstable.
Amortized O(1) insert and decrease-key, O(log n) extract. Complex; mainly theoretical (Dijkstra).
Each node has D children, so the tree is shallower: insert/decrease-key is faster (good for Dijkstra/Prim with many decrease-keys), but extract is slower because sift-down does up to D comparisons per level. D=4 is a common cache-friendly trade-off.
When you need to delete arbitrary elements or search by value → use balanced BST or hash map + heap.
List: O(V+E) space, good for sparse graphs (most real graphs). Matrix: O(V²) space, O(1) edge check, good for dense. Most graphs are sparse.
Directed edges have orientation; undirected stored both ways. Affects degree counts and traversal.
Weighted edges carry cost; choose Dijkstra/Bellman-Ford. Unweighted shortest path via BFS.
Queue-based level-order traversal. Shortest path in unweighted graphs. O(V+E).
from collections import deque
q=deque([src]); dist={src:0}
while q:
u=q.popleft()
for v in adj[u]:
if v not in dist:
dist[v]=dist[u]+1; q.append(v)
Stack/recursion-based. Used for components, cycle detection, topological sort, backtracking. O(V+E).
def dfs(u):
visited.add(u)
for v in adj[u]:
if v not in visited: dfs(v)
Linear ordering of DAG vertices such that edges point forward. Kahn's algorithm (BFS with indegrees) or DFS postorder reversed.
from collections import deque
indeg=[0]*n
for u in range(n):
for v in adj[u]: indeg[v]+=1
q=deque(i for i in range(n) if indeg[i]==0)
order=[]
while q:
u=q.popleft(); order.append(u)
for v in adj[u]:
indeg[v]-=1
if indeg[v]==0: q.append(v)
# if len(order)!=n: cycle
Directed: DFS with 3 colors (white/gray/black) or Kahn's (leftover vertices). Undirected: DFS skipping parent, or union-find.
Disjoint sets with path compression + union by rank. Near O(α(n)) ≈ O(1) amortized. Connectivity, Kruskal's MST, offline queries.
parent=list(range(n)); rank=[0]*n
def find(x):
while parent[x]!=x:
parent[x]=parent[parent[x]]; x=parent[x]
return x
def union(a,b):
ra,rb=find(a),find(b)
if ra==rb: return False
if rank[ra]<rank[rb]: ra,rb=rb,ra
parent[rb]=ra
if rank[ra]==rank[rb]: rank[ra]+=1
return True
Dijkstra (non-negative weights, heap) O((V+E) log V); Bellman-Ford (negative edges) O(VE); Floyd-Warshall (all-pairs) O(V³).
Kruskal: sort edges + DSU O(E log E). Prim: grow from a node with a min-heap O((V+E) log V).
BFS/DFS O(V+E) or union-find. For dynamic graphs, union-find is natural.
Kosaraju: DFS G recording finish order, then DFS the reversed graph in reverse finish order — each tree is one SCC. Tarjan: a single DFS with index/low-link values and a stack, O(V+E). SCCs give the condensation DAG, used for 2-SAT, cycle checks and reachability.
index, low, on, st, comps = {}, {}, set(), [], []
def dfs(u):
index[u] = low[u] = len(index)
st.append(u); on.add(u)
for v in adj[u]:
if v not in index:
dfs(v); low[u] = min(low[u], low[v])
elif v in on:
low[u] = min(low[u], index[v])
if low[u] == index[u]: # u is a root
comp = []
while True:
w = st.pop(); on.discard(w); comp.append(w)
if w == u: break
comps.append(comp)
Dijkstra plus a heuristic: expand by f(n) = g(n) + h(n), where g is the cost so far and h estimates the remaining cost. With an admissible (never overestimating) and consistent heuristic it stays optimal while expanding far fewer nodes; h=0 degenerates to Dijkstra. Grids use Manhattan or octile distance.
import heapq
def astar(start, goal, h):
g = {start: 0}
pq = [(h(start), 0, start)]
while pq:
f, gc, u = heapq.heappop(pq)
if u == goal: return gc
if gc > g.get(u, float('inf')): continue # stale entry
for v, w in adj[u]:
ng = gc + w
if ng < g.get(v, float('inf')):
g[v] = ng
heapq.heappush(pq, (ng + h(v), ng, v))
For graphs whose edge weights are only 0 or 1: use a deque, pushing 0-weight relaxations to the front and 1-weight to the back. The deque stays ordered by distance, so each edge is relaxed a constant number of times and the total is O(V+E) — faster than Dijkstra. Common for grids with free/blocked moves or 'break one wall' problems.
from collections import deque
dist = [float('inf')]*n; dist[src] = 0
dq = deque([src])
while dq:
u = dq.popleft()
for v, w in adj[u]: # w is 0 or 1
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
(dq.appendleft if w == 0 else dq.append)(v)
Hierholzer's algorithm walks unused edges and splices cycles; O(E). Undirected: all vertices with non-zero degree must be in one connected component, and either every degree is even (Eulerian circuit) or exactly two are odd (Eulerian path between them). Directed: non-zero-degree vertices must lie in one SCC, with in-degree = out-degree everywhere for a circuit, or exactly one vertex with out−in = 1 (start) and one with in−out = 1 (end) for a path.
A child map (or array of 26 for dense lowercase) plus an isEnd flag. Insert/search is O(L) for key length L, independent of how many keys are stored.
class TrieNode:
__slots__ = ('child', 'end')
def __init__(self):
self.child = {} # char -> TrieNode
self.end = False
Walk to the prefix node, then DFS to collect all words (optionally ranked by frequency).
Build a trie of words, DFS grid backtracking, prune matched branches. O(m*n*4^L) worst but pruning helps.
Use a hash map for sparse alphabets; array of size 26 for dense lowercase letters. Compressed trie merges single-child chains.
Merge chains of single-child nodes into one edge with a string label. Saves space; used in IP routing.
Stores all suffixes for substring search. Build O(n²) naive or O(n) with Ukkonen's algorithm.
Build trie of patterns + failure links (like KMP) for multi-pattern matching in O(text + patterns) total.
Binary trie of bits from MSB; find max XOR pair by choosing opposite bit at each level. O(32*n).
Unmark isEnd; remove nodes with no children on the path. Don't delete shared prefixes.
Trie supports prefix queries and ordered traversal; hash map is simpler and faster for exact lookup. Trie uses more memory.
Probabilistic set: bit array + multiple hash functions. False positives possible, no false negatives. Space-efficient membership testing.
Evict least frequently used; tie-break by recency. More complex than LRU (min-frequency bucket + doubly linked lists per frequency).
Probabilistic: multiple levels of linked lists. O(log n) expected search/insert; simpler than balanced trees; used in Redis.
Defer range updates to nodes; push down when needed. Range update + range query O(log n).
O(1) range min/max (idempotent ops) after O(n log n) preprocess; immutable data only.
Block size √n; range query/update O(√n). Simple alternative to segment tree.
High fan-out, disk-friendly. B+ tree leaves linked for range scans. Backbone of DB indexes.
Streaming approximations: frequency estimation and cardinality counting with small fixed memory.
Self-adjusting BST; recently accessed nodes moved to root. Amortized O(log n); good for temporal locality.
Tree of string chunks for efficient large-text editing (insert/delete O(log n)). Used in editors.
BST over intervals keyed by start, each node storing the max end in its subtree. To find overlaps with query q: descend left when left.max >= q.start, report a node when node.start <= q.end and node.end >= q.start, and check the right side. O(log n + k) for k hits; the classic structure for calendars, bookings and resource scheduling.
# Node fields: start, end, max_end (of subtree), left, right
def overlaps(node, lo, hi):
out = []
if node is None: return out
if node.left and node.left.max_end >= lo:
out += overlaps(node.left, lo, hi)
if node.start <= hi and lo <= node.end:
out.append((node.start, node.end))
if node.start <= hi:
out += overlaps(node.right, lo, hi)
return out
A BST by key plus a random min-heap priority per node. Expected O(log n) search/insert/delete with no rotation bookkeeping beyond split/merge; an implicit treap (indexed by subtree size instead of key) doubles as a sequence/rope with O(log n) split and concat.
import random
class Node:
__slots__ = ('key', 'prio', 'left', 'right')
def __init__(self, key):
self.key = key; self.prio = random.random()
self.left = self.right = None
def split(t, key): # (<= key, > key)
if t is None: return None, None
if t.key <= key:
a, b = split(t.right, key); t.right = a
return t, b
a, b = split(t.left, key); t.left = b
return a, t
def merge(a, b):
if not a or not b: return a or b
if a.prio < b.prio:
a.right = merge(a.right, b); return a
b.left = merge(a, b.left); return b
Use a half-open range [lo, hi) and keep the invariant 'answer is in [lo, hi]'. This template returns the first index whose value is >= target (lower bound) and never loops forever.
def lower_bound(a, target):
lo, hi = 0, len(a) # answer in [0, n]
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < target: lo = mid + 1
else: hi = mid
return lo # first i with a[i] >= target
lower_bound = first index with a[i] >= x; upper_bound = first index with a[i] > x. The count of x is upper - lower. Python's bisect_left / bisect_right are exactly these; bisect is O(log n).
from bisect import bisect_left, bisect_right
lo = bisect_left(a, x) # insert point, keeps order
hi = bisect_right(a, x)
count = hi - lo # occurrences of x
# a[lo:hi] is the whole run of x
First/last occurrence (lower/upper bound), search in a rotated sorted array (decide which half is sorted), search in an unbounded/growing array (double hi until a[hi] >= target), real-valued binary search (fixed ~100 iterations on the answer interval), and binary search over a monotone predicate (next item).
When the answer is a number and feasibility is monotone (if capacity c works, every c' > c works), binary search the value space and run an O(n) check. Turns many 'minimize the maximum' problems into O(n log range).
def feasible(cap): ... # monotone: True for cap >= answer
lo, hi = min_cap, max_cap
while lo < hi:
mid = lo + (hi - lo) // 2
if feasible(mid): hi = mid
else: lo = mid + 1
return lo
Infinite loops when lo = mid without shrinking, mid overflow (use lo + (hi-lo)//2), mixing inclusive/exclusive bounds, and forgetting that duplicates need lower/upper bound rather than 'found'. Always test n = 0, n = 1, and a hit at the last index.
Merge sort: O(n log n) always, stable, O(n) extra. Quicksort: O(n log n) average, O(n²) worst, in-place, unstable, best cache behavior. Heapsort: O(n log n) always, O(1) extra, unstable, poor cache. Insertion sort: O(n²) but O(n) on nearly sorted input, stable, ideal for small n. Timsort (Python/Java objects): O(n log n) worst, O(n) on runs, stable, O(n) extra. Counting/radix: O(n + k) or O(d(n + b)) for bounded integer keys, stable, not comparison-based.
Equal keys keep their original relative order. It matters when sorting by multiple fields: sort by the secondary key first, then stable-sort by the primary key, and ties keep the secondary order. Merge sort and Timsort are stable; quicksort and heapsort are not.
Partition like quicksort but recurse only into the side containing k: expected O(n), worst O(n²) with bad pivots; random pivots or median-of-medians give O(n) with high probability / guaranteed. Beats sorting when you only need one order statistic.
import random
def kth_smallest(a, k): # k is 0-based
lo, hi = 0, len(a) - 1
while True:
p = random.randint(lo, hi)
a[p], a[hi] = a[hi], a[p]
i = lo
for j in range(lo, hi):
if a[j] < a[hi]:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
if i == k: return a[i]
if i < k: lo = i + 1
else: hi = i - 1
Already-sorted input with a first/last pivot degrades to O(n²) — randomize or use median-of-three. Many equal keys also degrade a two-way partition; use a three-way (Dutch flag) partition. Recursion depth is O(log n) expected but O(n) worst; recurse into the smaller side and loop on the larger to bound stack use.
Comparison sorts cannot beat Ω(n log n), but non-comparison sorts can when keys are small integers or fixed-width: counting sort O(n + k), radix sort O(d(n + b)), bucket sort O(n) average for uniform keys. If you only need the top k, a heap (O(n log k)) or quickselect (O(n)) avoids a full sort.
Precompute the prefix function pi[i] = length of the longest proper prefix of p[0..i] that is also a suffix. On mismatch, fall back to pi[k-1] instead of restarting, so matching is O(n + m). Also finds all occurrences and gives the minimal period of a string.
def prefix(p):
pi, k = [0]*len(p), 0
for i in range(1, len(p)):
while k and p[i] != p[k]: k = pi[k-1]
if p[i] == p[k]: k += 1
pi[i] = k
return pi
def search(s, p):
pi, k, hits = prefix(p), 0, []
for i, ch in enumerate(s):
while k and ch != p[k]: k = pi[k-1]
if ch == p[k]: k += 1
if k == len(p):
hits.append(i - k + 1)
k = pi[k-1]
return hits
Hash every length-m window in O(1) by removing the outgoing character and adding the incoming one: h = (h - s[i]*B^(m-1)) * B + s[i+m] (mod M). Compare hashes first, then verify the substring on a match. Expected O(n + m), worst O(nm) with adversarial collisions.
def rabin_karp(s, p, B=256, M=(1 << 61) - 1):
n, m = len(s), len(p)
if m > n: return []
high = pow(B, m-1, M)
hp = hs = 0
for i in range(m):
hp = (hp*B + ord(p[i])) % M
hs = (hs*B + ord(s[i])) % M
hits = []
for i in range(n - m + 1):
if hs == hp and s[i:i+m] == p: hits.append(i)
if i < n - m:
hs = ((hs - ord(s[i])*high) * B + ord(s[i+m])) % M
return hits
Single-mod hashes are forgeable (anti-hash tests) and collide by birthday paradox around √M; use a large 64-bit modulus or double hashing with two primes. Always verify on a hash match. Never hash a mutable object, and randomize the base to defeat crafted inputs.
z[i] = length of the longest common prefix of s and s[i:], computed in O(n). Concatenate pattern + '#' + text and any z[i] == len(pattern) marks an occurrence; also handy for periodicity and prefix-matching problems.
def z_function(s):
z, l, r = [0]*len(s), 0, 0
for i in range(1, len(s)):
if i < r: z[i] = min(r - i, z[i - l])
while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r: l, r = i, i + z[i]
return z
heapq is a min-heap over a plain list: heappush/heappop O(log n), heapify O(n), nlargest/nsmallest O(n log k). There is no decrease-key or delete — push a duplicate entry and skip it when popped if its distance is stale. Build a max-heap by negating values, and add a counter as a tiebreaker so tuples never compare unorderable items.
import heapq
h = []
heapq.heappush(h, (dist, node))
d, u = heapq.heappop(h) # smallest tuple
heapq.heapify(h) # O(n), in place
heapq.nlargest(3, a) # top-3 without full sort
# max-heap: store -x
heapq.heappush(h, (-val, item))
# Dijkstra without decrease-key
# push (new_dist, v) again; on pop:
# if d > dist[u]: continue
deque: O(1) append/popleft at both ends (BFS, sliding window, maxlen). Counter: frequency map with most_common(k). defaultdict: missing keys auto-created by a factory (lists, sets, ints). OrderedDict: adds move_to_end and popitem(last=False) — the LRU primitive; a plain dict is already insertion-ordered in 3.7+. ChainMap: layered lookups (config overrides).
bisect_left/bisect_right give O(log n) search on a sorted list, while insort is O(n) because of the shift. Python has no built-in balanced BST or sorted dict: use sortedcontainers.SortedList/SortedDict/SortedSet (O(log n) insert/delete) when you need ordered updates, otherwise a heap or a re-sort.
dict preserves insertion order (3.7+) and gives O(1) average get/set/delete; set is unordered and not indexable. Keys must be hashable: list/dict are not, tuple/frozenset are (if their contents are). Mutating a dict while iterating raises RuntimeError — iterate over list(d) or a copy. No range queries: keep a sorted key list + bisect, or use SortedDict.
Always check before dereferencing; use Optional/nullable types and early returns.
Loops use < vs <=; array length n → last index n-1. Prefer half-open ranges [l, r).
Python default ~1000; C++ stack ~8MB. Convert deep recursion to iterative or raise the limit carefully.
Use 64-bit or Python big ints. Binary search mid = lo + (hi-lo)//2 avoids overflow.
Concurrent modification exceptions. Iterate over a copy or use iterator.remove().
Shallow copies share nested objects. Use deep copy for independent structures.
Avoid == on floats; use epsilon tolerance (abs(a-b) < eps).
Boxing primitives and per-object headers cost memory. Arrays of structs/primitives are leaner.
O(n²) may TLE for n=1e5; target O(n log n) or better. Check constraints first.
Handle base cases explicitly; many bugs occur at n=0 or n=1.
Clarify with the interviewer; duplicates affect binary search bounds and two-pointer logic.
Want this as flashcards? Study these 146 cards recall-first in the browser — flip, answer out loud, grade yourself.
What's new and the interview questions people are actually getting asked. No spam.