BTI Beyond The Interviews

DSA · 14 sections

DSA — Most Asked Patterns

The recurring patterns behind most DSA interview questions, starting with a signal -> pattern -> complexity lookup table you can scan mid-interview.

Free · full sheet 149 cards Updated 24 Oct 2026

Signal → Pattern → Complexity

"Sorted array + pair/triplet with target sum" → pattern?

Two pointers from both ends. O(n) for a pair, O(n²) for 3Sum (sort first, skip duplicates).

"Longest/shortest subarray/substring satisfying a condition" → ?

Sliding window (expand right, shrink left while the window is invalid), with a hashmap for counts. O(n).

"Subarray sum equals K" with negatives → ?

Prefix sum + hashmap of prefix counts: count += seen[prefix-k]. O(n). A sliding window fails with negatives.

"Next greater/smaller element", "stock span", "largest rectangle in histogram" → ?

Monotonic stack. Each element is pushed and popped once → O(n).

"Sliding window maximum" → ?

Monotonic deque of indices (decreasing values). Pop from the front when out of the window. O(n).

"Top K / Kth largest" → ?

Min-heap of size K: O(n log k). Quickselect gives O(n) average. Bucket sort for frequencies, O(n).

"Minimise the maximum" / "smallest capacity such that…" → ?

Binary search on the answer + greedy feasibility check. O(n log range). E.g. Koko bananas, ship packages, split array.

"Rotated sorted array search" → ?

Modified binary search. One half is always sorted; check whether the target lies in it. O(log n).

"Shortest path in an unweighted grid/graph" → ?

BFS, O(V+E). Multi-source BFS for "rotting oranges" / distance to the nearest X. 0-1 BFS with a deque for 0/1 weights.

Weighted shortest path, non-negative vs negative weights?

Dijkstra with a heap, O((V+E) log V). With negative weights: Bellman-Ford O(VE) (detects negative cycles). All pairs: Floyd-Warshall O(V³).

"Course schedule / build order / dependencies" → ?

Topological sort: Kahn's BFS with indegrees. A cycle exists if processed count < V. O(V+E).

"Number of connected components / dynamic connectivity / redundant edge" → ?

Union-Find with path compression + union by rank → ~O(α(n)) per operation.

"All subsets / permutations / combinations / N-Queens" → ?

Backtracking: choose → recurse → un-choose. Subsets O(2ⁿ·n), permutations O(n!·n). Prune early.

"Count ways / min cost / can you reach" with overlapping subproblems → ?

DP. Define the state, transition and base case. Top-down memoisation or bottom-up. Space-optimise to O(1)/O(n) when only the previous row is needed.

Two strings, "edit distance / LCS / interleaving" → ?

2D DP dp[i][j] over prefixes. O(m·n) time, reducible to O(min(m,n)) space.

"Merge overlapping intervals / meeting rooms" → ?

Sort by start, then merge: O(n log n). For the minimum number of rooms, use a min-heap of end times or a sweep over sorted starts/ends.

"Linked list cycle / middle / kth from end" → ?

Fast and slow pointers. Floyd's algorithm: after meeting, reset one pointer to head and move both by 1 to find the cycle start. O(n), O(1) space.

"Prefix search / word dictionary / autocomplete" → ?

Trie: insert/search O(L). Combine with DFS for Word Search II.

"Range sum with updates" → ?

Fenwick tree (BIT) or segment tree: O(log n) for both update and query. A prefix sum array only works without updates.

"Find the single number / missing number" → ?

XOR trick (a⊕a = 0), O(1) space. Missing number = n(n+1)/2 − sum, or XOR of indices and values.

"Tree: LCA / diameter / path sum" → ?

Post-order DFS that returns information up from the children (height, found flags). Diameter = max over nodes of left height + right height. O(n).

Constraint size → target complexity?

n ≤ 10 → n!. n ≤ 20 → 2ⁿ. n ≤ 500 → n³. n ≤ 5,000 → n². n ≤ 10⁶ → n log n or n. n ≤ 10¹⁸ → log n / math. (~10⁸ simple operations per second.)

Two Pointers

Two pointers (opposite ends)?

Start at both ends of a sorted array, move inward based on condition. O(n). Used for pairs summing to target, palindrome, container with most water.

lo, hi = 0, n-1
while lo < hi:
  if a[lo] + a[hi] == target: return (lo, hi)
  if a[lo] + a[hi] < target: lo += 1
  else: hi -= 1

Two pointers (same direction / fast-slow)?

Fast pointer explores; slow marks valid write position. O(n). Used for remove duplicates, move zeros, partition.

Fast/slow pointers for cycle detection?

Floyd: slow moves 1, fast moves 2. Meeting implies cycle; reset one to head and advance both by 1 to find entry.

slow = fast = head
while fast and fast.next:
  slow = slow.next
  fast = fast.next.next
  if slow is fast: # cycle
    slow = head
    while slow is not fast:
      slow = slow.next; fast = fast.next
    return slow  # entry

Dutch national flag (three pointers)?

Partition array into 0s, 1s, 2s in one pass with low/mid/high pointers. O(n) time, O(1) space.

Container with most water?

Two pointers at ends; area = min(h[l],h[r])*(r-l). Move the shorter side inward. O(n).

Trapping rain water (two pointers)?

Track leftMax/rightMax; water at i = min(leftMax,rightMax)-h[i]. Move side with smaller max. O(n), O(1) space.

3-sum / 4-sum pattern?

Sort, then fix one (or two) elements and two-pointer the rest. 3-sum O(n²), 4-sum O(n³). Skip duplicates.

Merge sorted arrays in-place?

Two pointers from the end of the combined buffer; fill from back to avoid overwriting. O(m+n).

Squares of a sorted array?

Two pointers from both ends; compare squares, fill result from the back. O(n).

When NOT to use two pointers?

When array is unsorted and sorting cost is unacceptable, or when you need all pairs (O(n²) unavoidable).

Two pointers on strings (palindrome)?

Compare from both ends moving inward; skip non-alphanumeric if needed. O(n).

Complexity summary?

Two-pointer scans are O(n) after any required sort O(n log n). Space O(1) extra.

Sliding Window

Fixed-size sliding window?

Maintain window of size K; slide by adding new element and removing old. O(n). Used for max sum subarray of size K, anagrams.

Variable-size sliding window?

Expand right; shrink left while constraint violated. Each element added/removed once → O(n). Used for longest substring without repeating, min window substring.

Character frequency window (anagrams)?

Use an array of 26 counts (or a Counter); compare counts or track a 'matches' counter. O(n) instead of O(n*K) for the naive re-count of every window.

from collections import Counter
def checkInclusion(s1, s2):
  n = len(s1)
  if n > len(s2): return False
  need, win = Counter(s1), Counter(s2[:n])
  if win == need: return True
  for i in range(n, len(s2)):
    win[s2[i]] += 1                    # add the entering char
    left = s2[i-n]
    win[left] -= 1                     # remove the leaving char
    if win[left] == 0: del win[left]   # keep counts comparable
    if win == need: return True
  return False

At most K distinct characters?

Expand right; when distinct > K, shrink left until valid. Track counts; decrement distinct when count hits 0.

Longest substring without repeating?

Sliding window with last-occurrence map; jump left to max(left, last[c]+1). O(n).

Minimum window substring?

Expand right until valid (all needed chars covered); shrink left while still valid; record min. O(n + m).

Sliding window max/min?

Monotonic deque of indices with decreasing values: pop the back while the new element dominates, pop the front when it leaves the window. Each index enters/leaves once, so O(n). Used for sliding window maximum, shortest subarray with sum >= K, constrained subsequences.

from collections import deque
def max_sliding_window(a, k):
  dq, out = deque(), []                 # dq holds indices, values decreasing
  for i, x in enumerate(a):
    while dq and a[dq[-1]] <= x: dq.pop()
    dq.append(i)
    if dq[0] <= i - k: dq.popleft()     # front is out of the window
    if i >= k - 1: out.append(a[dq[0]])
  return out

Subarray sum equals K (positive numbers)?

Sliding window with two pointers (sum grows monotonically). For arbitrary integers use prefix sum + hash map.

Fixed vs variable window distinction?

Fixed: window size known (K). Variable: window size determined by a condition; shrink/grow dynamically.

Off-by-one in window indices?

Window [left, right] inclusive has size right-left+1. Be consistent; prefer [left, right) half-open for easier sizing.

Sliding window on circular array?

Duplicate the array (concatenate) and run window of length n, or use modulo indexing.

Amortized complexity?

Each element is added and removed at most once, so O(n) total even with nested while loops.

Binary Search

Standard binary search?

lo=0, hi=n-1; mid=lo+(hi-lo)//2 (avoids overflow). Compare and halve. O(log n).

lo, hi = 0, n-1
while lo <= hi:
  mid = lo + (hi-lo)//2
  if a[mid] == target: return mid
  if a[mid] < target: lo = mid+1
  else: hi = mid-1
return -1

Lower bound (first ≥ target)?

First index where a[i] >= target. Use lo < hi, mid=(lo+hi)//2; if a[mid] < target: lo=mid+1 else hi=mid.

Upper bound (first > target)?

First index where a[i] > target. Symmetric to lower bound with strict comparison.

Search in rotated sorted array?

Identify which half is sorted by comparing mid to ends; check if target lies in sorted half; recurse. O(log n).

Find peak element?

Compare mid with mid+1; if a[mid] < a[mid+1] peak is right else left. O(log n).

Binary search on answer?

When feasibility is monotonic (if x works, every larger x works), binary search the answer space instead of the array: check a candidate in O(n), total O(n log(range)). Canonical problems: Koko eating bananas, ship package capacity, split array largest sum / painter partition, aggressive cows, minimum days to make bouquets. Beware overflow in lo+hi and pick the right 'first true' template.

lo, hi = min_ans, max_ans
while lo < hi:
  mid = (lo+hi)//2
  if feasible(mid): hi = mid
  else: lo = mid+1
return lo

Ternary search?

For unimodal functions, split into thirds. O(log n) but larger constant than binary; rarely needed.

Exponential search?

For unbounded (streaming/infinite) or huge sorted arrays: double the bound 1, 2, 4, 8, ... until a[hi] >= target, then binary search inside [hi/2, hi]. Cost is O(log i) where i is the target's position, not O(log n) — you never touch elements past it, which is the whole point on unbounded input. O(1) extra space.

def exp_search(a, x):            # a sorted, possibly unbounded
  if a[0] == x: return 0
  hi = 1
  while hi < len(a) and a[hi] < x: hi *= 2
  lo, hi = hi // 2, min(hi, len(a) - 1)
  while lo <= hi:
    mid = (lo + hi) // 2
    if a[mid] == x: return mid
    if a[mid] < x: lo = mid + 1
    else: hi = mid - 1
  return -1

bisect module (Python)?

bisect_left/right implement lower/upper bound. Use for sorted lists; O(log n).

Off-by-one: lo < hi vs lo <= hi?

Use lo <= hi with mid±1 for exact search; lo < hi with mid (no ±1) for bound search. Pick based on update rule.

Infinite loop pitfall?

Ensure mid rounds down and at least one bound moves each iteration. Use mid = lo + (hi-lo)//2.

Search a 2D sorted matrix?

Two different matrices, two different algorithms. (1) Rows and columns sorted individually, not end-to-end (LeetCode 240): a staircase walk from the top-right or bottom-left — move left if the value is too big, down if too small. O(m+n); this is NOT binary search. (2) Fully sorted row-major (last of each row < first of the next, LeetCode 74): treat the matrix as one flat array of m*n elements and binary search with mid -> (mid//n, mid%n) in O(log mn).

def search_matrix(mat, target):   # rows fully sorted end-to-end
  m, n = len(mat), len(mat[0])
  lo, hi = 0, m*n - 1
  while lo <= hi:
    mid = (lo + hi) // 2
    v = mat[mid // n][mid % n]
    if v == target: return True
    if v < target: lo = mid + 1
    else: hi = mid - 1
  return False

BFS & DFS

BFS level-order traversal?

Queue; process level by level using size snapshot. Used for level averages, right side view, rotten oranges.

from collections import deque
q = deque([root])
while q:
  for _ in range(len(q)):
    node = q.popleft()
    if node.left: q.append(node.left)
    if node.right: q.append(node.right)

DFS recursive/iterative?

Recursive is simplest; iterative uses explicit stack. Preorder/inorder/postorder. Watch recursion depth.

Connected components?

BFS/DFS over all unvisited nodes; count traversals. Or union-find for dynamic graphs.

Shortest path in unweighted graph?

BFS from source; distance = number of edges. Multi-source BFS for nearest source.

Backtracking via DFS (template)?

Choose, explore (recurse), unchoose. Prune early. Used for permutations, N-queens, Sudoku, word search.

In-place visited marking?

Mutate grid (e.g., set to '0' or '#') to avoid visited set; restore if needed. Saves O(mn) space.

Topological sort (Kahn's)?

Kahn's BFS on indegrees: queue every indegree-0 node, pop and decrement neighbors; the pop order is a valid topological order. If fewer than n nodes come out, the graph has a cycle. DFS alternative: postorder reversed is also topological; a gray->gray edge means a cycle. O(V+E).

from collections import deque
def topo(n, edges):
  adj, indeg = [[] for _ in range(n)], [0]*n
  for u, v in edges:
    adj[u].append(v); 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)
  return order if len(order) == n else []   # [] => cycle

Cycle detection in directed graph?

DFS with 3 colors: white unvisited, gray in stack, black done. Gray→gray edge = cycle.

Multi-source BFS?

Seed the queue with every source at distance 0, then run plain BFS: each node is settled at its distance to the nearest source. O(V+E) instead of one BFS per source. Used for rotten oranges, 01 matrix, walls and gates, and 'distance to nearest gate/land' grids.

from collections import deque
def multi_source(adj, sources):
  q = deque(sources)
  dist = {s: 0 for s in sources}
  while q:
    u = q.popleft()
    for v in adj[u]:
      if v not in dist:
        dist[v] = dist[u] + 1
        q.append(v)
  return dist

0-1 BFS?

Deque: push weight-0 edges to front, weight-1 to back. Shortest path with 0/1 weights in O(V+E).

Bidirectional BFS?

Search from both source and target simultaneously; meet in middle. Faster for large state spaces.

Recursion depth issues?

Deep DFS can stack-overflow. Convert to iterative or increase limit; Python default ~1000.

Graphs & Trees (Advanced)

Dijkstra (non-negative weights)?

Greedy: repeatedly settle the closest unsettled node and relax its edges. Binary heap gives O((V+E) log V); skip stale heap entries instead of implementing decrease-key. Fails with negative edges, because a settled node can later get a cheaper path. On a grid with arbitrary costs it is BFS with a priority queue.

import heapq
def dijkstra(adj, src):
  dist = {src: 0}
  pq = [(0, src)]
  while pq:
    d, u = heapq.heappop(pq)
    if d > dist[u]: continue            # stale entry
    for v, w in adj[u]:
      nd = d + w
      if nd < dist.get(v, float('inf')):
        dist[v] = nd
        heapq.heappush(pq, (nd, v))
  return dist

Bellman-Ford (negative edges / negative cycles)?

Relax every edge V-1 times: after pass k you have the shortest paths using at most k edges. O(V*E). One extra pass that still relaxes proves a reachable negative cycle (then shortest paths are undefined). Early-exit when a pass changes nothing. SPFA is the queue-based variant: fast in practice, O(V*E) worst case. Used for arbitrage detection and distance-vector routing.

def bellman_ford(n, edges, src):
  dist = [float('inf')]*n; dist[src] = 0
  for _ in range(n-1):
    changed = False
    for u, v, w in edges:
      if dist[u] + w < dist[v]:
        dist[v] = dist[u] + w; changed = True
    if not changed: break
  for u, v, w in edges:                     # nth pass => negative cycle
    if dist[u] + w < dist[v]: return None
  return dist

Floyd-Warshall (all-pairs shortest paths)?

dp[k][i][j] = best i->j path using intermediates from {0..k}. k must be the OUTER loop. O(V^3) time, O(V^2) space (updated in place). Handles negative edges, and dist[i][i] < 0 detects a negative cycle. Best for dense graphs with small V (up to a few hundred); for sparse graphs run Dijkstra from each node instead.

INF = float('inf')
d = [[INF]*n for _ in range(n)]
for i in range(n): d[i][i] = 0
for u, v, w in edges: d[u][v] = min(d[u][v], w)
for k in range(n):
  for i in range(n):
    for j in range(n):
      if d[i][k] + d[k][j] < d[i][j]:
        d[i][j] = d[i][k] + d[k][j]

Which shortest-path algorithm should I use?

Unweighted -> BFS, O(V+E). Weights 0/1 -> 0-1 BFS with a deque. Non-negative weights -> Dijkstra. Negative edges -> Bellman-Ford, or a single topological relaxation pass if the graph is a DAG (O(V+E)). All pairs on a small dense graph -> Floyd-Warshall. Unit-cost grid -> BFS; weighted grid -> Dijkstra. Unweighted with many queries from one source -> BFS once and cache the distances.

Tree DP (subtree / rerooting)?

Root the tree, then compute dp[u] by combining the children's answers in postorder: O(n) total. Examples: max path sum, diameter (two largest child depths through u), house robber III, subtree sizes, count nodes at distance k. Rerooting computes down[u] from the children, then a second pass pushes the parent's 'outside' answer into each child, giving an all-nodes answer in O(n). Watch recursion depth on skewed trees.

def diameter(adj, root=0):
  best = 0
  def dfs(u, p):
    nonlocal best
    top1 = top2 = 0
    for v in adj[u]:
      if v == p: continue
      h = dfs(v, u) + 1
      if h > top1: top1, top2 = h, top1
      elif h > top2: top2 = h
    best = max(best, top1 + top2)        # path through u
    return top1
  dfs(root, -1)
  return best

LCA with binary lifting?

Precompute up[k][u] = the 2^k-th ancestor and depth[u] in one DFS: O(n log n) time and space. Query: lift the deeper node to the same depth, then lift both from the highest k downward while their ancestors differ; the answer is up[0][u]. O(log n) per query. Distance between nodes = depth[u] + depth[v] - 2*depth[lca]. Alternatives: Euler tour + sparse table (O(1) queries) or offline Tarjan.

LOG = max(1, n.bit_length())
up = [parent[:]]                       # up[0][u] = parent(u); root points to itself
for k in range(1, LOG):
  prev = up[k-1]
  up.append([prev[prev[u]] for u in range(n)])

def lca(u, v):
  if depth[u] < depth[v]: u, v = v, u
  diff = depth[u] - depth[v]
  for k in range(LOG):
    if diff >> k & 1: u = up[k][u]
  if u == v: return u
  for k in reversed(range(LOG)):
    if up[k][u] != up[k][v]:
      u, v = up[k][u], up[k][v]
  return up[0][u]

Dynamic Programming

Memoization (top-down)?

Recursive function with cache (lru_cache/dict). Natural state transitions; only computes reachable states.

Tabulation (bottom-up)?

Fill DP table iteratively from base cases. Avoids recursion; often more space-efficient and faster.

How to define DP state?

dp[i] = best answer for prefix of length i. Identify subproblems and transition; ensure optimal substructure.

1D DP examples?

Climbing stairs, house robber, max subarray (Kadane), coin change. dp[i] depends on previous few values.

2D DP (grid paths, edit distance)?

dp[i][j] for position (i,j). Transitions from top/left or insert/delete/replace. O(mn).

0/1 knapsack?

dp[w] = max value with capacity w; iterate items outer, capacity inner descending to avoid reuse. O(nW).

dp = [0]*(W+1)
for weight, val in items:
  for w in range(W, weight-1, -1):
    dp[w] = max(dp[w], dp[w-weight]+val)

Unbounded knapsack?

Same as 0/1 but iterate capacity ascending, allowing reuse of an item multiple times.

Longest common subsequence (LCS)?

dp[i][j] = dp[i-1][j-1]+1 if a[i-1]==b[j-1] else max(dp[i-1][j], dp[i][j-1]). O(mn).

Longest increasing subsequence (LIS)?

O(n²) DP or O(n log n) via patience sorting (binary search on tails).

Matrix chain multiplication (interval DP)?

dp[i][j] = min over k of dp[i][k]+dp[k+1][j]+cost. O(n³).

State compression (bitmask DP)?

Use a bitmask as the state for small n (<= ~20): subset/mask problems, assignment problems, TSP, counting Hamiltonian paths. dp[mask][i] = best value for the visited set `mask` ending at i, O(2^n * n^2) time and O(2^n * n) space; pure dp[mask] is O(2^n * n) when the last element does not matter. Enumerate submasks with (sub-1) & mask.

INF = float('inf')
dp = [[INF]*n for _ in range(1 << n)]      # TSP: min cost, visited mask, ending at i
for i in range(n): dp[1 << i][i] = 0
for mask in range(1 << n):
  for i in range(n):
    if not (mask >> i) & 1 or dp[mask][i] == INF: continue
    for j in range(n):
      if (mask >> j) & 1: continue
      nm = mask | (1 << j)
      dp[nm][j] = min(dp[nm][j], dp[mask][i] + cost[i][j])

Space optimization?

If dp[i] depends only on previous row, keep two rows (or one with careful order). Reduces O(n²) to O(n).

Greedy

Greedy choice property?

A locally optimal choice leads to globally optimal solution. Must verify; not all problems allow greedy.

Interval scheduling (activity selection)?

Sort by end time; pick if start ≥ last end. Maximizes count of non-overlapping intervals. O(n log n).

Merge intervals?

Sort by start, then sweep: if the next start <= current end, extend end = max(end, next end); otherwise push the current interval and start a new one. O(n log n) for the sort, O(n) for the sweep. Variants: insert interval (three phases: before, overlap, after); meeting rooms II (min-heap of end times, or a sweep over sorted start/end events); erase-overlap-intervals (sort by end, greedy count).

def merge(intervals):
  out = []
  for s, e in sorted(intervals):
    if out and s <= out[-1][1]:
      out[-1][1] = max(out[-1][1], e)
    else:
      out.append([s, e])
  return out

Huffman coding?

Combine two smallest frequencies repeatedly using a min-heap. Optimal prefix code. O(n log n).

Jump game?

Track farthest reachable index; if i > farthest return false. O(n).

Gas station?

If total gas ≥ total cost, a solution exists; find start where running sum never goes negative. O(n).

Fractional vs 0/1 knapsack?

Fractional: greedy by value/weight works. 0/1: greedy fails; use DP.

Minimum coins (canonical systems)?

Greedy works for canonical coin systems (e.g., US coins). For arbitrary denominations use DP.

Task scheduler with cooldown?

Count max frequency; answer = max(len(tasks), (maxfreq-1)*(cooldown+1)+count_of_max).

Proof techniques for greedy?

Exchange argument: show any optimal solution can be transformed to greedy without decreasing value.

When greedy fails?

When local choice blocks better global arrangement (e.g., 0/1 knapsack). Test small counterexamples.

Backtracking

Backtracking template?

def backtrack(path, choices): if base: record; return. for c in choices: choose; backtrack; unchoose. Prune early.

Permutations?

Two templates. used[] array: pick any unused element, mark it, recurse, unmark — O(n*n!) time, and the only one where duplicate skipping works cleanly: sort first, then skip when i > 0 and a[i] == a[i-1] and not used[i-1] (the earlier twin is already used at this level). Swap-based (in-place): swap a[i] into position i, recurse, swap back — no sorting shortcut here; dedupe with a per-level seen set, or skip a[i] if it already appeared at this depth.

def permute(a):
  a.sort(); out, path = [], []
  used = [False]*len(a)
  def bt():
    if len(path) == len(a):
      out.append(path[:]); return
    for i in range(len(a)):
      if used[i]: continue
      if i > 0 and a[i] == a[i-1] and not used[i-1]: continue
      used[i] = True; path.append(a[i])
      bt()
      path.pop(); used[i] = False
  bt(); return out

Combinations?

Start index parameter to avoid reusing and duplicates; choose current, recurse with i+1, then unchoose. O(C(n,k)*k).

Subsets?

For each element include or exclude; or build by adding element and recursing from next index. 2^n subsets.

N-Queens?

Place queen per row; check columns and both diagonals via sets. Backtrack when conflict. O(n!) worst.

Sudoku solver?

Find empty cell; try digits 1-9 validating row/column/box; recurse; undo on failure.

Word search on grid?

DFS from each cell matching first char; mark visited in-place; restore on backtrack.

Pruning strategies?

Sort + skip duplicates; bound (branch and bound); check feasibility before recursing. Crucial for performance.

Complexity?

Often exponential (O(b^d) or O(n!)); pruning is what makes it pass. Memoize if subproblems overlap → DP.

Iterative deepening?

DFS with increasing depth limit; combines DFS memory efficiency with BFS completeness.

Constraint propagation?

Reduce domains before search (e.g., Sudoku naked singles) to shrink branching.

Backtracking vs DP?

Backtracking explores all possibilities; DP memoizes overlapping subproblems. If subproblems repeat, use DP.

Divide & Conquer

Merge sort?

Divide array in half, sort recursively, merge. O(n log n) time, O(n) space, stable.

def merge_sort(a):
  if len(a)<=1: return a
  m=len(a)//2
  L=merge_sort(a[:m]); R=merge_sort(a[m:])
  return merge(L,R)

Quick sort?

Partition around pivot; recurse on both sides. Average O(n log n), worst O(n²) if bad pivot. In-place, unstable.

Pivot selection?

Random or median-of-three avoids worst case on sorted input. Hoare/Lomuto partition schemes.

Closest pair of points?

Sort by x; divide; conquer; combine by checking points within δ of midline sorted by y. O(n log n).

Karatsuba multiplication?

Split numbers; compute 3 products instead of 4. O(n^1.585).

Strassen matrix multiplication?

7 multiplications instead of 8 for 2x2 blocks. O(n^2.81).

Binary search as D&C?

Divide search space by comparing mid; conquer one half. O(log n).

Master theorem?

Analyzes recurrences T(n)=aT(n/b)+f(n). Determines asymptotic growth by comparing f(n) to n^(log_b a).

Inversion count?

Merge sort variant: count when taking element from right half before left. O(n log n).

Maximum subarray (D&C)?

O(n log n); but Kadane's O(n) is better. D&C useful for teaching.

Linked Lists

Reverse a linked list (iterative)?

Three pointers: prev = None, cur = head. Save nxt = cur.next, point cur.next at prev, then advance both. O(n) time, O(1) space. This is the base case for reverse-in-k-group, palindrome linked list, add two numbers and reorder list.

def reverse(head):
  prev, cur = None, head
  while cur:
    nxt = cur.next
    cur.next = prev
    prev, cur = cur, nxt
  return prev

Reverse a linked list (recursive / in k-groups)?

Recursive: new_head = reverse(head.next); head.next.next = head; head.next = None — O(n) stack space. In k-groups: check that k nodes remain, reverse that block, then connect the block's tail (the old head) to the result of the rest. O(n) time, O(1) space iteratively. The same pointer surgery solves reverse-between-m-and-n.

def reverse_k(head, k):
  cur, cnt = head, 0
  while cur and cnt < k:
    cur = cur.next; cnt += 1
  if cnt < k: return head               # fewer than k left: leave as is
  prev, cur = None, head
  for _ in range(k):
    nxt = cur.next
    cur.next = prev
    prev, cur = cur, nxt
  head.next = reverse_k(cur, k)         # head is now the block's tail
  return prev

LRU cache design?

Hash map key -> node plus a doubly linked list ordered by recency: get moves a node to the tail, put inserts/updates at the tail, eviction removes the head. O(1) per operation, O(capacity) space. In Python an OrderedDict (or a plain dict, 3.7+ preserves insertion order) gives it directly: move_to_end on a hit, popitem(last=False) to evict. Interview follow-ups: LFU, thread safety, TTL.

from collections import OrderedDict

class LRUCache:
  def __init__(self, cap):
    self.cap, self.d = cap, OrderedDict()
  def get(self, k):
    if k not in self.d: return -1
    self.d.move_to_end(k)
    return self.d[k]
  def put(self, k, v):
    if k in self.d: self.d.move_to_end(k)
    self.d[k] = v
    if len(self.d) > self.cap:
      self.d.popitem(last=False)          # evict least recently used

Strings & Hashing

KMP (substring search)?

Precompute lps[i] = length of the longest proper prefix of p[:i+1] that is also a suffix. On a mismatch fall back to lps[j-1] instead of restarting, so the text pointer never moves backwards: O(n+m) time, O(m) space. The same prefix function solves repeated substring pattern, string period (n - lps[-1]), and shortest palindrome.

def kmp(text, pat):
  def lps(p):
    out, l, i = [0]*len(p), 0, 1
    while i < len(p):
      if p[i] == p[l]: l += 1; out[i] = l; i += 1
      elif l: l = out[l-1]
      else: out[i] = 0; i += 1
    return out
  f, j, hits = lps(pat), 0, []
  for i, c in enumerate(text):
    while j and c != pat[j]: j = f[j-1]
    if c == pat[j]: j += 1
    if j == len(pat):
      hits.append(i - j + 1)
      j = f[j-1]
  return hits

Rolling hash / Rabin-Karp?

Hash a window of length m in O(1): remove the leaving char, add the entering one, mod a large prime. O(n+m) expected time for substring search, duplicate-substring and anagram-window problems, and longest duplicate substring (binary search on the length). Always pair a single hash with a verification step or use double hashing — collisions break correctness, and an adversary can force them.

def rabin_karp(text, pat, base=911382323, mod=(1 << 61) - 1):
  n, m = len(text), len(pat)
  if m > n: return -1
  power = pow(base, m-1, mod)
  h = t = 0
  for i in range(m):
    h = (h*base + ord(text[i])) % mod
    t = (t*base + ord(pat[i])) % mod
  for i in range(n - m + 1):
    if h == t and text[i:i+m] == pat: return i
    if i < n - m:
      h = ((h - ord(text[i])*power) * base + ord(text[i+m])) % mod
  return -1

Which substring search should I use?

One-off search -> the built-in (str.find / indexOf), which is fast in practice but can degrade to O(n*m) in naive implementations. Guaranteed O(n+m) -> KMP or Z-function. Many patterns against one text -> Aho-Corasick (trie + failure links). Duplicate-substring / window-equality problems -> rolling hash. Tiny alphabet and short pattern -> plain O(n*m) scan is fine.

Bit Manipulation

Basic bitwise operations?

AND &, OR |, XOR ^, NOT ~, shifts << >>. Operate on binary representation.

Check if bit k is set?

(n >> k) & 1. O(1).

Set/clear/toggle bit k?

Set: n | (1<<k). Clear: n & ~(1<<k). Toggle: n ^ (1<<k).

XOR tricks?

a^a=0, a^0=a. Find unique element among pairs: XOR all. Missing number: XOR 0..n with array.

Power of two check?

n > 0 and (n & (n-1)) == 0. Clears lowest set bit; result 0 iff single bit.

Count set bits (Brian Kernighan)?

while n: n &= n-1; count++. Runs in O(number of set bits).

Subset enumeration?

Iterate mask from 0 to (1<<n)-1; each mask is a subset. O(2^n * n) to enumerate elements.

Enumerate submasks of a mask?

for sub = mask; sub; sub = (sub-1) & mask visits every submask in O(2^popcount(mask)); summed over all masks that is O(3^n), fine for n <= ~20. Used for partition-style bitmask DP (assign tasks to workers, palindrome partitioning, subset-sum enumeration).

sub = mask
while sub:
  # ... use sub ...
  sub = (sub - 1) & mask
# note: this skips sub == 0; handle the empty submask separately if needed

Arithmetic via bits?

Add without + using carry: a^b sum bits, (a&b)<<1 carry; repeat until carry 0.

Signed vs logical right shift?

Java/JS: >> is arithmetic (sign-extending), >>> is logical (zero-fill) — and JS has no >>> for BigInt. C/C++: right-shifting a negative signed value is implementation-defined, so cast to unsigned first. Python has no >>>: ints are arbitrary-precision, >> is arithmetic, and -1 >> 1 == -1, so mask before shifting (e.g. (n & 0xFFFFFFFF) >> 1) to emulate a 32-bit logical shift. Endianness is byte order in memory and is unrelated to shifts.

Gray code?

g = n ^ (n >> 1). Consecutive values differ by one bit; used in rotary encoders.

Bitwise vs logical operators?

Bitwise operates on bits (&,|,^); logical (&&,||) short-circuits on truthiness. Don't confuse in conditions.

Common Patterns

Prefix sums?

pre[i]=sum first i; range sum [l,r]=pre[r+1]-pre[l] in O(1). 2D prefix for matrix sums.

Difference array?

Range add [l,r] += v in O(1): diff[l]+=v, diff[r+1]-=v; reconstruct via prefix sum.

Monotonic stack?

Maintain increasing/decreasing order; pop while violated. Next greater element, largest rectangle in histogram. O(n).

Union-Find?

Near O(1) amortized connectivity; used in Kruskal MST, dynamic connectivity, offline queries.

Heap / priority queue?

heapq is a min-heap in Python (negate keys for a max-heap); push/pop O(log n), heapify O(n), peek O(1). Used for Dijkstra and Prim, k-way merge, running median (two heaps), task scheduling, and bounded top-K (see the Top-K card).

Trie?

Prefix search, autocomplete, word search, max XOR pair, Aho-Corasick multi-match.

Segment tree / Fenwick?

Range query + point/range update in O(log n). Fenwick simpler; segment tree more flexible.

Two pointers + hash?

Pair sums, anagrams, sliding windows with lookup. Combine for O(n) solutions.

Top-K with a heap (code)?

Keep a min-heap of size k: push each element, pop when the size exceeds k. O(n log k) time and O(k) space — better than sorting when k << n. The heap holds the k largest; its root is the k-th largest. For k closest points use a max-heap of distance (negate). Quickselect is O(n) average but O(n^2) worst case. heapq.nlargest/nsmallest is the built-in shortcut.

import heapq
def top_k(a, k):
  h = []
  for x in a:
    heapq.heappush(h, x)
    if len(h) > k: heapq.heappop(h)      # keep only the k largest
  return sorted(h, reverse=True)

# heapq.nlargest(k, a) / heapq.nsmallest(k, a) do the same thing

Cyclic sort (values in 1..n)?

When the array holds 1..n (or 0..n-1), put every value at its own index by swapping until a[i] == i+1, then scan for the first mismatch. O(n) time, O(1) space, because each swap places one value permanently. Solves first missing positive, missing number, find all duplicates and find all disappeared numbers.

def cyclic_sort(a):
  i, n = 0, len(a)
  while i < n:
    v = a[i]
    if 1 <= v <= n and a[v-1] != v:
      a[i], a[v-1] = a[v-1], a[i]   # swap v into place, retry i
    else:
      i += 1
  return a

Want this as flashcards? Study these 149 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck