All sheets / Interview Core
DSA Patterns
Recognize the pattern, then apply the template. Examples in Python.
Big-O at a glance
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Hash map | n/a | O(1) avg | O(1) avg | O(1) avg |
| Linked list | O(n) | O(n) | O(1) at node | O(1) at node |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) |
| Heap | O(1) top | O(n) | O(log n) | O(log n) |
Sorting O(n log n); binary search O(log n); BFS/DFS O(V + E).
Which pattern?
| Clue | Pattern |
|---|---|
| sorted array, pair/target | two pointers / binary search |
| contiguous subarray/substring | sliding window / prefix sum |
| top/kth/smallest k | heap |
| all combinations/permutations | backtracking |
| shortest path, unweighted | BFS |
| connectivity, islands, groups | DFS / union-find |
| dependencies, ordering | topological sort |
| overlapping subproblems, min/max/count ways | dynamic programming |
| next greater/smaller | monotonic stack |
| intervals | sort by start, merge |
| prefix lookups | trie |
Two pointers
def two_sum_sorted(a, target):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target: return l, r
if s < target: l += 1
else: r -= 1Sliding window
def longest_unique(s):
seen, l, best = {}, 0, 0
for r, ch in enumerate(s):
if ch in seen and seen[ch] >= l:
l = seen[ch] + 1
seen[ch] = r
best = max(best, r - l + 1)
return bestBinary search
def lower_bound(a, x): # first index with a[i] >= x
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x: lo = mid + 1
else: hi = mid
return loAlso "binary search on the answer": min capacity/speed where feasible(mid) flips.
Prefix sum & hashing
def subarray_sum_k(nums, k): # count subarrays summing to k
count, s, seen = 0, 0, {0: 1}
for n in nums:
s += n
count += seen.get(s - k, 0)
seen[s] = seen.get(s, 0) + 1
return countBFS / DFS
from collections import deque
def bfs(grid, start):
q, seen = deque([(start, 0)]), {start}
while q:
(r, c), d = q.popleft()
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#' and (nr, nc) not in seen:
seen.add((nr, nc)); q.append(((nr, nc), d + 1))
def dfs(node, graph, seen):
seen.add(node)
for nxt in graph[node]:
if nxt not in seen: dfs(nxt, graph, seen)Trees
def max_depth(root):
return 0 if not root else 1 + max(max_depth(root.left), max_depth(root.right))
def level_order(root):
out, q = [], deque([root] if root else [])
while q:
out.append([n.val for n in q])
q = deque(c for n in q for c in (n.left, n.right) if c)
return outInorder of a BST is sorted. Validate BST by passing (lo, hi) bounds down.
Heap / top-k
import heapq
def top_k(nums, k): # k largest, O(n log k)
h = []
for n in nums:
heapq.heappush(h, n)
if len(h) > k: heapq.heappop(h)
return hTopological sort
def topo(n, edges): # Kahn's algorithm
g, indeg = defaultdict(list), [0] * n
for a, b in edges: g[a].append(b); indeg[b] += 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 g[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order if len(order) == n else [] # [] = cycleUnion-find
parent = list(range(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
parent[ra] = rb; return TrueBacktracking
def subsets(nums):
out = []
def go(i, path):
if i == len(nums): out.append(path[:]); return
go(i + 1, path) # skip
path.append(nums[i]); go(i + 1, path); path.pop() # take
go(0, []); return outDynamic programming
def coin_change(coins, amount): # min coins
dp = [0] + [float('inf')] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a: dp[a] = min(dp[a], dp[a - c] + 1)
return dp[amount] if dp[amount] != float('inf') else -1Steps: define state → recurrence → base cases → order (top-down memo or bottom-up) → optimize space.
Monotonic stack & intervals
def next_greater(a):
res, st = [-1] * len(a), []
for i, x in enumerate(a):
while st and a[st[-1]] < x: res[st.pop()] = x
st.append(i)
return res
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 outLRU cache
from collections import OrderedDict
class LRU:
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):
self.d[k] = v; self.d.move_to_end(k)
if len(self.d) > self.cap: self.d.popitem(last=False)Coding round checklist
- Restate the problem, confirm inputs/outputs and edge cases.
- Give a brute force + its complexity.
- Optimize using a pattern; state time/space.
- Code cleanly, narrating.
- Test with examples + edge cases (empty, one item, duplicates, negatives).