Linear Structures
01 In-place Arrays and Sorting 数组原地操作与排序
Read/write pointers for in-place compaction · O(n) time · O(1) space
Key points
- Everything left of the write pointer w is final; the read pointer only scans forward, so each pointer moves once.
- Decide whether to keep a value by comparing it with nums[w-k], the kept result, not with the previous raw element.
- When merging two sorted arrays in place, write from the back so you never overwrite unread data.
Common pitfalls
- The judge reads only the first k slots; return the new length and never rely on anything past it.
- Deleting while iterating (list.remove, ArrayList.remove) is O(n²) and skips elements.
- A comparator written as a - b overflows near ±2^31; use Integer.compare or a plain < comparison.
def keep_at_most(nums: list[int], k: int) -> int:
"""Sorted nums: keep each value at most k times, in place. Returns the new length."""
w = 0
for x in nums:
if w < k or nums[w - k] != x:
nums[w] = x
w += 1
return w
02 Hash Counting and Relationship Modeling 哈希计数与关系建模
One-pass hash map lookup · O(n) time · O(n) space
Key points
- Query the complement before storing the current value: one pass finds earlier partners and never pairs an element with itself.
- Store what the question needs: an index for positions, a count for how many, and the first index only when you need the earliest.
- Keys can be built: a sorted string, a count tuple or a (row, value) pair puts everything of one kind into one bucket.
Common pitfalls
- Inserting before querying pairs an element with itself when target equals 2x.
- In C++, map[key] on a missing key inserts a default value; use find or count to test membership.
- In Java, comparing two Integer objects with == can fail above 127; use equals or unbox to int first.
def two_sum(nums: list[int], target: int) -> tuple[int, int]:
seen: dict[int, int] = {}
for i, x in enumerate(nums):
if target - x in seen:
return seen[target - x], i
seen[x] = i
return -1, -1
03 String Parsing and Matching 字符串解析与匹配
KMP prefix function · O(n + m) time · O(m) space
Key points
- pi[i] is the length of the longest proper prefix of pat[0..i] that is also its suffix; on a mismatch j falls back to pi[j-1] and the text pointer never moves back.
- Building pi and scanning the text are the same loop: building the table is the pattern matching against itself.
- For parsing tasks, advance one index by hand over digits, signs and brackets; edge cases are easier than with split.
Common pitfalls
- After a full match set j = pi[j-1]; otherwise you miss overlapping occurrences ("aa" occurs 3 times in "aaaa").
- Concatenating strings with + in a loop is O(n²); collect pieces and join in Python, use StringBuilder in Java.
- In Go, s[i] is a byte and len(s) counts bytes; convert to []rune for multi-byte text such as Chinese.
def find_all(text: str, pat: str) -> list[int]:
"""Start index of every occurrence of a non-empty pat in text."""
m = len(pat)
pi = [0] * m
j = 0
for i in range(1, m):
while j and pat[i] != pat[j]:
j = pi[j - 1]
if pat[i] == pat[j]:
j += 1
pi[i] = j
res, j = [], 0
for i, c in enumerate(text):
while j and c != pat[j]:
j = pi[j - 1]
if c == pat[j]:
j += 1
if j == m:
res.append(i - m + 1)
j = pi[j - 1]
return res
04 Two Pointers and Sliding Windows 双指针与滑动窗口
Variable-size sliding window · O(n) time · O(Σ) space
Key points
- The right end advances every step and the left end moves only while the window is invalid; both only go forward, so the total is O(n).
- For the longest window, update the answer after shrinking; for the shortest, update it inside the shrink loop while the window is still valid.
- On sorted arrays use opposite-end pointers for pair sums, dedupe and reversal; use fast/slow pointers for cycles and midpoints.
Common pitfalls
- Forgetting to decrement the count of the element leaving the window desynchronises the window state.
- With negative numbers "shrink when the sum exceeds k" is no longer monotonic and the window breaks; use prefix sums instead.
- "Exactly k" is awkward to slide directly; compute at-most(k) minus at-most(k-1).
from collections import defaultdict
def longest_unique(s: str) -> int:
"""Length of the longest substring without repeated characters."""
cnt = defaultdict(int)
left = best = 0
for right, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
05 Prefix Sums and Intervals 前缀和与区间
Prefix sums with a hash count · O(n) time · O(n) space
Key points
- A range sum is the difference of two prefix sums: sum(l..r) = pre[r+1] - pre[l]; allocate one extra slot with pre[0] = 0.
- When counting subarrays that sum to k, seed the map with {0: 1} for subarrays that start at index 0.
- For many range updates use a difference array (diff[l] += v, diff[r+1] -= v, then one prefix pass); to merge intervals, sort by left end first.
Common pitfalls
- Without the {0: 1} seed you miss every subarray that starts at index 0.
- Prefix sums overflow 32-bit integers easily; use long long in C++ and long in Java.
- Storing the current prefix before querying counts the empty subarray when k = 0.
def count_subarrays(nums: list[int], k: int) -> int:
"""Number of non-empty subarrays whose sum is k (negatives allowed)."""
seen = {0: 1}
pre = ans = 0
for x in nums:
pre += x
ans += seen.get(pre - k, 0)
seen[pre] = seen.get(pre, 0) + 1
return ans
06 Binary Search and Answer Search 二分查找与答案二分
First true on a half-open range · O(log n) checks
Key points
- Rewrite the problem as a monotonic check ok(x), false then true, and search for the first true.
- On the half-open range [lo, hi): set hi = mid when ok(mid), else lo = mid + 1; loop while lo < hi, and lo is the answer at the end.
- When the answer's range is known and a candidate can be checked in O(n), binary search the answer itself: minimum speed, maximise the minimum and so on.
Common pitfalls
- lo = mid with a rounded-down mid loops forever; with this template only ever write lo = mid + 1.
- (lo + hi) / 2 can overflow in C++, Java and Go; write lo + (hi - lo) / 2.
- hi itself is never checked: pick an upper bound that is surely feasible, or a returned hi gets mistaken for an answer.
from typing import Callable
def first_true(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
"""Smallest x in [lo, hi) with ok(x), where ok goes False..False True..True; hi if none."""
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid
else:
lo = mid + 1
return lo
def lower_bound(nums: list[int], target: int) -> int:
"""First index whose value is >= target (len(nums) if none)."""
return first_true(0, len(nums), lambda i: nums[i] >= target)
07 Stacks, Monotonic Deques, and Heaps 栈、单调队列与堆
Monotonic stack: next greater element · O(n) time · O(n) space
Key points
- Keep indexes on the stack, not values: you can still read the value and also measure distances such as days until a warmer day.
- Each element is pushed and popped once, so the nested while is still O(n) overall.
- For the top k keep a min-heap of size k; for sliding-window maxima use a monotonic deque and drop the front once it leaves the window.
Common pitfalls
- With duplicates, < and <= give different answers; decide whether you need strictly greater or greater-or-equal.
- Python's heapq is a min-heap only; push negated values to get a max-heap.
- Java's Stack class is slow and synchronized; use ArrayDeque for stacks and queues, and don't write comparators as a - b.
def next_greater(nums: list[int]) -> list[int]:
"""For each i, the first value to the right that is strictly greater, or -1."""
ans = [-1] * len(nums)
stack = []
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x
stack.append(i)
return ans
08 Greedy Algorithms and Scheduling 贪心与调度
Sort by end time, keep what fits · O(n log n) time
Key points
- Always take the interval that ends first; it leaves the most room. Exchange argument: the first pick of any optimal answer can be swapped for it without loss.
- Minimum removals = total minus the maximum kept; "minimum arrows" is the same loop, except that touching endpoints count as overlapping.
- Before writing a greedy, state why the local choice never hurts; if you can't, the problem probably needs DP.
Common pitfalls
- Sorting by start time lets one long interval that starts early block everything else.
- Whether touching endpoints overlap depends on the problem; >= versus > is one character and a different answer.
- A comparator written as a[1] - b[1] overflows near ±2^31.
def max_non_overlapping(intervals: list[list[int]]) -> int:
"""Most intervals you can keep with no overlap; [a, b] and [b, c] may touch."""
count, end = 0, float("-inf")
for start, finish in sorted(intervals, key=lambda iv: iv[1]):
if start >= end:
count += 1
end = finish
return count
Lists & Trees
09 Linked Lists and Pointers 链表与指针
Reverse in place, fast and slow pointers · O(n) time · O(1) space
Key points
- Save next before rewiring. Reversal is three moves: save next, point back, step forward.
- When the head may be removed or replaced, start from a dummy node that points at head and return dummy.next.
- A fast pointer taking two steps per slow step finds the middle and detects a cycle; for the k-th node from the end, move a lead pointer k steps first, then advance both at the same speed.
Common pitfalls
- Rewiring head.next before saving it loses the rest of the list.
- Check that fast and fast.next are non-null before touching fast.next.next.
- After splitting a list, forgetting to null out the first half's tail creates a cycle when you merge or traverse.
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def reverse(head):
prev = None
while head:
nxt = head.next
head.next = prev
prev, head = head, nxt
return prev
def middle(head):
"""Middle node; the second of the two middles for even lengths."""
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
10 Binary Tree Traversal and Structure 二叉树遍历与结构
Level-order BFS · O(n) time · O(width) space
Key points
- Record the queue length at the start of each round; processing exactly that many nodes separates one level from the next.
- Before writing a recursive DFS, decide what a subtree returns (depth, balance, size); the answer is always a merge of left and right.
- Pre-, in- and post-order differ only in whether you handle the current node before, between or after the two recursive calls.
Common pitfalls
- Using the live queue length as the loop bound mixes the next level into the current one.
- list.pop(0) is O(n) in Python; use collections.deque for queues.
- A degenerate tree recurses 10^5 levels deep and overflows Python's stack; go iterative or raise the recursion limit.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def level_order(root) -> list[list[int]]:
if not root:
return []
levels, q = [], deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
for child in (node.left, node.right):
if child:
q.append(child)
levels.append(level)
return levels
11 Tree Paths and Recursive Aggregation 树上路径与递归汇总
Return the one-sided gain, record the bent path globally · O(n) time · O(h) stack
Key points
- The recursion returns the best one-sided downward path, because a path that continues upward can use only one child.
- The path that bends at the node (left + node + right) only updates the global answer; it is never returned to the parent.
- For root-to-leaf paths, add on entry and remove on exit; for path sums starting anywhere, use prefix sums with a hash map.
Common pitfalls
- Initialising the answer to 0 is wrong when every value in the tree is negative.
- Clamp a negative child gain to 0 (don't take that side), or it drags the answer down.
- Returning the bent path to the parent lets a path fork, which overcounts.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_path_sum(root) -> int:
"""Largest sum of any non-empty path between two nodes."""
best = float("-inf")
def gain(node) -> int:
nonlocal best
if not node:
return 0
left, right = max(gain(node.left), 0), max(gain(node.right), 0)
best = max(best, node.val + left + right)
return node.val + max(left, right)
gain(root)
return best
12 Binary Tree Construction and Transformation 二叉树构造与变换
Preorder picks the root, inorder splits the sides · O(n) time · O(n) space
Key points
- The first preorder value is the root; find it in inorder, and everything to its left is the left subtree, everything to its right the right subtree.
- A value-to-inorder-index map makes each split O(1) and the whole build O(n).
- Recursing left before right, the next preorder value is always the next root, so no lengths are needed; with postorder plus inorder, read from the back and build right before left.
Common pitfalls
- With duplicate values the inorder position is ambiguous and this method breaks.
- Copying subarrays at every level (Python slices, Java copyOfRange) degrades the build to O(n²).
- With postorder plus inorder, building the left subtree first takes the roots in the wrong order.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build_tree(preorder: list[int], inorder: list[int]):
"""Rebuild a tree with distinct values from its preorder and inorder walks."""
pos = {v: i for i, v in enumerate(inorder)}
roots = iter(preorder)
def build(lo: int, hi: int):
if lo == hi:
return None
root = TreeNode(next(roots))
mid = pos[root.val]
root.left = build(lo, mid)
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder))
13 Binary Search Trees 二叉搜索树
Iterative inorder walks a BST in sorted order · O(h + k) time · O(h) space
Key points
- An inorder walk of a BST is sorted, so k-th smallest, validation and predecessor/successor all become inorder problems.
- To validate a BST, pass (lo, hi) bounds down; every node must sit strictly inside the range its ancestors allow.
- Search and insert follow a single path, O(h): O(log n) when balanced and O(n) on a chain.
Common pitfalls
- Comparing a node only with its children misses a small value deep in the right subtree.
- Using INT_MIN/INT_MAX as bounds fails when a node holds that exact value; use long or null for "unbounded".
- Forgetting to move to node.right in the iterative walk repeats nodes or stops early.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def kth_smallest(root, k: int) -> int:
"""1-indexed; assumes 1 <= k <= number of nodes."""
stack, node = [], root
while True:
while node:
stack.append(node)
node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.val
node = node.right
Graphs
14 Grid Traversal and Multisource Search 网格遍历与多源搜索
Multi-source BFS, one ring per step · O(rows × cols)
Key points
- Enqueue every source at the start, as if from one virtual super source; the BFS layer is the shortest distance.
- Mark a cell visited when it is enqueued, so it is never added twice.
- For connected components (island count, area) DFS or BFS both work; for the fewest steps you need BFS.
Common pitfalls
- Marking on dequeue lets several neighbours enqueue the same cell, which times out on large grids.
- When nothing is fresh at the start the answer is 0, not -1 and not the layer count.
- Recursive DFS on a 1000×1000 grid overflows the stack; use BFS or an explicit stack.
from collections import deque
def minutes_to_rot(grid: list[list[int]]) -> int:
"""0 empty, 1 fresh, 2 rotten. Minutes until nothing is fresh, or -1."""
rows, cols = len(grid), len(grid[0])
q = deque((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 2)
fresh = sum(row.count(1) for row in grid)
minutes = 0
while q and fresh:
minutes += 1
for _ in range(len(q)):
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
return -1 if fresh else minutes
15 Graph Connectivity and Union-Find 图连通性与并查集
Union-find with path compression and union by size · ≈ O(α(n)) per operation
Key points
- Compress paths in find and hang the smaller tree under the larger in union; together each operation is close to constant time.
- union returning false means the two ends were already connected, which is how you detect cycles and redundant edges.
- Keep per-component data such as size only on the root and add it up when merging.
Common pitfalls
- parent[a] == parent[b] does not mean connected; compare find(a) == find(b).
- Writing parent[a] = b instead of linking the two roots corrupts the structure.
- When nodes are strings or coordinates, map them to 0..n-1 first, or keep parent in a hash map.
class DSU:
def __init__(self, n: int):
self.parent = list(range(n))
self.size = [1] * n
self.count = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
a, b = self.find(a), self.find(b)
if a == b:
return False
if self.size[a] < self.size[b]:
a, b = b, a
self.parent[b] = a
self.size[a] += self.size[b]
self.count -= 1
return True
16 Topological Sorting and Dependencies 拓扑排序与依赖关系
Kahn's algorithm: dequeue zero in-degree nodes · O(V + E)
Key points
- A node with in-degree 0 has no unfinished prerequisites; place it, then decrement the in-degree of everything it points to.
- If fewer than n nodes come out, the rest sit on a cycle; that is the whole check for course-schedule problems.
- For the lexicographically smallest order, replace the queue with a min-heap.
Common pitfalls
- Reading an edge backwards ("a depends on b" means b → a) reverses the whole order.
- Enqueuing only the nodes that start at in-degree 0 and forgetting the ones that drop to 0 later.
- A DFS topological sort with only visited/unvisited cannot see cycles; it needs a third "in progress" state.
from collections import deque
def topo_order(n: int, edges: list[tuple[int, int]]) -> list[int]:
"""Edge (u, v) means u comes before v. Returns [] if there is a cycle."""
graph = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
graph[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 graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == n else []
17 Shortest Paths and Graph States 最短路径与图状态
Dijkstra with a heap and lazy deletion · O((V + E) log V)
Key points
- The node popped with the smallest tentative distance is final; this only holds when every edge weight is non-negative.
- Skip decrease-key: push the new distance and, on pop, discard entries larger than dist (lazy deletion).
- With 0/1 weights use deque BFS; with negative weights use Bellman-Ford; when the state carries extra data such as stops used, treat (node, count) as the node.
Common pitfalls
- Not skipping stale heap entries relaxes the same node again and again and times out on dense graphs.
- Distances outgrow 32-bit integers, and INT_MAX used as infinity turns negative once w is added.
- Building a directed graph as undirected (or the reverse) makes every distance wrong.
import heapq
def dijkstra(n: int, edges: list[tuple[int, int, int]], src: int) -> list[int]:
"""Directed edges (u, v, w) with w >= 0. Unreachable nodes get -1."""
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
dist = [float("inf")] * n
dist[src] = 0
heap = [(0, src)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in graph[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return [d if d != float("inf") else -1 for d in dist]
18 Spanning Trees and Tree Graphs 生成树与树形图
Kruskal: sort the edges, join with union-find · O(E log E)
Key points
- Go through the edges from lightest to heaviest; take an edge if it joins two different components, otherwise skip it (it would close a cycle).
- n-1 chosen edges form a spanning tree; fewer than that means the graph is disconnected.
- On dense graphs such as all pairs of points, the O(n²) form of Prim is often faster than sorting every edge.
Common pitfalls
- Returning the summed weight without checking that every node got connected.
- All pairs of points give n²/2 edges, which can exceed both the memory and the time limit for sorting.
- Nodes numbered from 1 overflow a union-find sized n by one.
def mst_weight(n: int, edges: list[tuple[int, int, int]]) -> int:
"""Undirected edges (u, v, w). Weight of a minimum spanning tree, or -1 if disconnected."""
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
total = used = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
ru, rv = find(u), find(v)
if ru != rv:
parent[ru] = rv
total += w
used += 1
return total if used == n - 1 else -1
Backtracking
19 Backtracking Enumeration and Deduplication 回溯枚举与去重
Choose, recurse, undo; skip duplicates on the same level · O(n · 2^n)
Key points
- The template is three moves: choose, recurse, undo. path is a single buffer shared by the whole search.
- Sort first, then skip with i > start && nums[i] == nums[i-1]: a value is not reused on the same level, but deeper levels may use it.
- Combinations pick from start onward so {1,2} and {2,1} don't both appear; permutations scan from the beginning with a used array.
Common pitfalls
- Storing a reference to path leaves every result as the same empty list once the search finishes.
- Writing i > 0 instead of i > start also skips legitimate repeats on deeper levels.
- Forgetting to sort leaves equal values apart, and the duplicate check does nothing.
def subsets_with_dup(nums: list[int]) -> list[list[int]]:
nums = sorted(nums)
res, path = [], []
def dfs(start: int) -> None:
res.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
dfs(i + 1)
path.pop()
dfs(0)
return res
20 String Partitioning and Construction 字符串拆分与构造
Backtrack over cut points with a palindrome table · O(n · 2^n)
Key points
- Each level decides where the next piece ends; when start reaches n you have one complete split.
- Precompute an O(n²) table of which substrings are palindromes so each check inside the search is O(1).
- Restoring IP addresses and word break use the same frame; only the "is this piece valid" test changes.
Common pitfalls
- Re-checking palindromes with two pointers inside the search repeats work and inflates the constant.
- If you only need the number of ways or the fewest cuts, don't enumerate; use DP.
- Keep one convention for substring bounds; s[start:end+1] and substring(start, end+1) are easy to get off by one.
def partition(s: str) -> list[list[str]]:
"""Every way to cut s into palindromes."""
n = len(s)
pal = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
res, path = [], []
def dfs(start: int) -> None:
if start == n:
res.append(path[:])
return
for end in range(start, n):
if pal[start][end]:
path.append(s[start : end + 1])
dfs(end + 1)
path.pop()
dfs(0)
return res
21 Constraint Search and Pruning 约束搜索与剪枝
N-Queens: prune by column and both diagonals · O(n!) worst case
Key points
- Place one queen per row so the search branches only on columns; mark columns, diagonals (r-c) and anti-diagonals (r+c) in three arrays.
- Prune as early as possible: test for conflicts before recursing, not after the board is full.
- For sudoku and combination-sum style problems, sort first and break as soon as the remaining values cannot work; break saves far more than continue.
Common pitfalls
- The diagonal index r-c can be negative; offset it by n-1.
- Forgetting to clear the marks before returning wrongly prunes every later branch.
- When printing boards, edit a mutable character buffer and convert it once at the end instead of copying the whole board at every step.
def total_queens(n: int) -> int:
"""Number of ways to place n non-attacking queens on an n x n board."""
cols, diag, anti = [False] * n, [False] * (2 * n - 1), [False] * (2 * n - 1)
def place(r: int) -> int:
if r == n:
return 1
count = 0
for c in range(n):
d = r - c + n - 1
if cols[c] or diag[d] or anti[r + c]:
continue
cols[c] = diag[d] = anti[r + c] = True
count += place(r + 1)
cols[c] = diag[d] = anti[r + c] = False
return count
return place(0)
Dynamic Programming
22 Dynamic Programming Fundamentals and State Design 动态规划入门与状态设计
1-D DP with rolling variables · O(n) time · O(1) space
Key points
- Define the state in one sentence, such as dp[i] = the best answer using the first i elements; once that is precise, the transition usually follows.
- Derive the transition from the last decision: take element i or not, last jump of 1 step or 2.
- When dp[i] depends only on the previous one or two values, roll two variables and cut space from O(n) to O(1).
Common pitfalls
- dp and input indexes drift apart: with one extra slot dp[0] means "nothing chosen yet" and the answer is dp[n].
- When rolling, overwriting prev1 before computing the new value means you read the updated value by mistake.
- Counts quickly outgrow 64 bits; when the problem asks for a modulus, apply it at every step.
def rob(nums: list[int]) -> int:
"""Largest sum of elements with no two adjacent."""
prev2 = prev1 = 0
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1
23 Grid Paths and Two-Dimensional States 网格路径与二维状态
Grid DP compressed to one row · O(rows × cols) time · O(cols) space
Key points
- dp[r][c] depends only on the cells above and to the left, so fill row by row, left to right, in one array: before the update dp[c] is "above" and dp[c-1] is "left".
- The first row and column have a single source; handle them separately or use an infinity sentinel.
- To count paths, replace min with addition and set obstacle cells to 0.
Common pitfalls
- Adding a cell value to an INT_MAX sentinel overflows; only ever add to finite values.
- If moves can go in all four directions there is no fill order and DP fails; use BFS or Dijkstra.
- After compressing to one row, save the top-left value in a variable before it is overwritten if the transition needs it.
def min_path_sum(grid: list[list[int]]) -> int:
"""Cheapest path from top-left to bottom-right moving only right or down."""
cols = len(grid[0])
dp = [float("inf")] * cols
dp[0] = 0
for row in grid:
for c in range(cols):
left = dp[c - 1] if c else float("inf")
dp[c] = min(dp[c], left) + row[c]
return dp[-1]
24 Knapsack and Combination Counting 背包与组合计数
0/1 knapsack backwards, unbounded forwards · O(n × target)
Key points
- The 0/1 knapsack loops capacity downwards so dp[s-x] is still the value without x; the unbounded version loops upwards so an item can be reused.
- Items outside and capacity inside counts combinations (order ignored); capacity outside and items inside counts permutations.
- Many problems reduce to a knapsack: equal-sum partition asks whether sum/2 is reachable, and target sum asks for (sum+target)/2.
Common pitfalls
- Looping a 0/1 knapsack forwards uses the same item many times.
- For counting, dp[0] = 1 (choosing nothing is one way); for min/max, dp[0] = 0 and everything else starts at infinity.
- Reducing to (sum+target)/2 without checking parity and sign gives a bad index.
def count_subsets(nums: list[int], target: int) -> int:
"""Ways to pick a subset (each item at most once) that sums to target."""
dp = [1] + [0] * target
for x in nums:
for s in range(target, x - 1, -1):
dp[s] += dp[s - x]
return dp[target]
def count_combinations(coins: list[int], amount: int) -> int:
"""Ways to make amount with unlimited coins, order ignored."""
dp = [1] + [0] * amount
for coin in coins:
for s in range(coin, amount + 1):
dp[s] += dp[s - coin]
return dp[amount]
25 Subsequences and Partial Orders 子序列与偏序关系
LIS with a tails array and binary search · O(n log n)
Key points
- tails[k] is the smallest possible tail of an increasing subsequence of length k+1; it is itself sorted, so you can binary search it.
- Strictly increasing uses lower_bound (first ≥ x); non-decreasing uses upper_bound (first > x).
- For 2-D nesting such as envelopes, sort by width ascending and by height descending on ties, then run LIS on the heights.
Common pitfalls
- tails is not an actual longest subsequence, only its length is right; record predecessors if you must output one.
- Using the wrong bound for strict versus non-strict is off by one or more on inputs with many duplicates.
- Counting how many longest subsequences there are needs the O(n²) dp with a count array.
from bisect import bisect_left
def lis_length(nums: list[int]) -> int:
"""Length of the longest strictly increasing subsequence."""
tails = []
for x in nums:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
26 String Matching and Editing 字符串匹配与编辑
Two-string DP over prefixes · O(m × n)
Key points
- dp[i][j] is defined on prefixes, the first i characters of a and the first j of b, with an extra row and column for the empty string.
- If the last characters match, inherit dp[i-1][j-1]; otherwise replace, delete and insert map to the diagonal, upper and left cells.
- Longest common subsequence, distinct subsequences and wildcard matching all use this table with different transitions.
Common pitfalls
- dp indexes are prefix lengths, so the matching character is a[i-1]; writing a[i] is off by one.
- Forgetting row 0 and column 0: reaching the empty string takes i deletions, building from it takes j insertions.
- In a one-row version the diagonal value is overwritten by the current row; keep it in a separate variable.
def edit_distance(a: str, b: str) -> int:
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
27 Palindromes and Interval States 回文与区间状态
Interval DP with the left end running backwards · O(n²)
Key points
- dp[i][j] depends only on shorter ranges, dp[i+1][*] and dp[*][j-1], so fill i backwards and j forwards.
- If the two ends match, shrink inward and add 2; otherwise drop one end and keep the better of the two.
- For palindromic substrings (contiguous), expanding around each center is simpler: O(n²) time and O(1) space.
Common pitfalls
- Iterating i forwards reads dp[i+1][*] before it has been computed.
- Subsequence (gaps allowed) and substring (contiguous) are different problems with different transitions.
- Center expansion must try both odd centers (i, i) and even centers (i, i+1).
def longest_pal_subseq(s: str) -> int:
n = len(s)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1] if n else 0
28 State Machines and Contiguous Sequences 状态机与连续序列
Ending-at-i states: track both max and min · O(n) time · O(1) space
Key points
- Define the state as "ending at i"; a contiguous subarray then has two transitions: extend the previous run or restart at i.
- A negative factor turns the maximum into the minimum, so keep both a max state and a min state.
- State-machine DP gives each position a few states (holding or not, previous taken or not) and writes out every transition between them.
Common pitfalls
- Updating hi first and then computing lo from the new hi mixes values from the same step.
- Starting the answer at 0 is wrong for an all-negative array.
- Kadane's maximum subarray sum uses cur = max(x, cur + x); don't drop the restart option.
def max_product(nums: list[int]) -> int:
"""Largest product of a non-empty contiguous subarray."""
hi = lo = best = nums[0]
for x in nums[1:]:
cand = (x, hi * x, lo * x)
hi, lo = max(cand), min(cand)
best = max(best, hi)
return best
29 Stock Trading State Machines 股票交易状态机
Three states: holding, cooling down, free · O(n) time · O(1) space
Key points
- Name the states you can be in at the end of a day, then list which state yesterday plus which action today reaches each one.
- All of today's values must come from yesterday's, so assign them simultaneously or through temporaries.
- At most k trades adds a k dimension; a fee is charged once per sale (or purchase); a single trade is just tracking the lowest price so far.
Common pitfalls
- Starting the holding state at 0 means you got a share for free on day 0.
- With negative infinity as the start value, hold + p overflows in C++ and Java; use something like MIN / 2.
- With a cooldown you can buy only from the free state, never straight after selling.
def max_profit_cooldown(prices: list[int]) -> int:
"""Unlimited trades, but after selling you must wait one day before buying."""
hold, cool, free = float("-inf"), 0, 0
for p in prices:
hold, cool, free = (
max(hold, free - p),
hold + p,
max(free, cool),
)
return max(cool, free)
30 Partitioning and Scheduling Optimization 分段与调度优化
Sort by end, binary search the last compatible job · O(n log n)
Key points
- After sorting by end time, dp[i] is the best over the first i jobs; job i is either skipped or appended after the last job that doesn't overlap it.
- Find the last compatible job by binary searching the end times, for O(n log n) overall.
- "Split the array into k parts" problems usually use dp[parts][end] and enumerate where the last part starts.
Common pitfalls
- Whether touching endpoints conflict decides between upper_bound and lower_bound.
- Sorting by start time and greedily taking the highest profit fails once jobs carry weights.
- Sorting only the end times without moving the start times and profits along with them.
from bisect import bisect_right
def max_profit(start: list[int], end: list[int], profit: list[int]) -> int:
"""Best total profit of non-overlapping jobs; a job may start when another ends."""
jobs = sorted(zip(end, start, profit))
ends = [e for e, _, _ in jobs]
dp = [0] * (len(jobs) + 1)
for i, (_, s, p) in enumerate(jobs):
k = bisect_right(ends, s, 0, i)
dp[i + 1] = max(dp[i], dp[k] + p)
return dp[-1]
31 Path, Tree, and Game States 路径、树形与对抗状态
Tree DP: each node returns (take, skip) · O(n)
Key points
- Tree DP runs post-order: get both children's results first, then compute the current node, returning a small tuple.
- Splitting the state by whether the current node is taken is simpler than looking two levels down from the parent, and nothing is computed twice.
- Two-player games often use the score difference for the player to move: dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]).
Common pitfalls
- The grandparent-plus-grandchildren version without memoization repeats work exponentially.
- When the node is skipped the children are free, so take max(take, skip) for each child, not just take.
- Modelling a game by "my score" usually forces you to track the opponent as well; the difference is simpler.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def rob_tree(root) -> int:
"""Largest sum of node values with no parent-child pair both taken."""
def dfs(node) -> tuple[int, int]:
if not node:
return 0, 0
lt, ls = dfs(node.left)
rt, rs = dfs(node.right)
take = node.val + ls + rs
skip = max(lt, ls) + max(rt, rs)
return take, skip
return max(dfs(root))
Design & Bits
32 Container and Iterator Design 容器与迭代接口设计
Lazy iterator: hasNext does the advancing · O(1) amortised per call
Key points
- Put "skip empty rows and reach the next valid element" in hasNext and let next only read; calling hasNext repeatedly then has no side effects.
- Keep only positions (row and column) instead of copying every element into one big array in the constructor.
- For arbitrarily nested lists keep a stack of positions, one per level; in Python a generator with yield from is the natural fit.
Common pitfalls
- With empty rows in the middle or at the end, looking only at the next row makes hasNext return a wrong true.
- A next that doesn't call hasNext first reads out of bounds.
- Modifying the container while iterating throws ConcurrentModificationException in Java and fails silently elsewhere.
class Flatten2D:
"""Iterates a list of lists in order, skipping empty rows."""
def __init__(self, rows: list[list[int]]):
self.rows, self.r, self.c = rows, 0, 0
def has_next(self) -> bool:
while self.r < len(self.rows) and self.c == len(self.rows[self.r]):
self.r, self.c = self.r + 1, 0
return self.r < len(self.rows)
def next(self) -> int:
if not self.has_next():
raise StopIteration
self.c += 1
return self.rows[self.r][self.c - 1]
33 Caches, Random Access, and Streaming Indexes 缓存、随机访问与流式索引
LRU: hash map plus doubly linked list · O(1) get and put
Key points
- The hash map finds a node in O(1); the doubly linked list moves it to the front and drops the tail in O(1).
- A get counts as a use and moves the node to the most recent end; put on an existing key updates and moves it instead of inserting a second copy.
- When you must hand-roll the list, sentinel head and tail nodes remove every null check.
Common pitfalls
- Evicting the tail from the list but not from the map, or the other way round.
- Decide once whether you insert then evict or evict then insert, and think through edge cases such as capacity 0.
- Without the key stored in the list node you can't tell which map entry to delete on eviction.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.data = OrderedDict()
def get(self, key: int) -> int:
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key: int, value: int) -> None:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False)
34 Dictionaries, File Systems, and Serialization 字典、文件系统与序列化
Trie nodes hold children and counts · O(length) per operation
Key points
- Each node is a prefix; insert and lookup walk down one character at a time, so the cost depends only on the word length.
- Counts on the nodes (words passing through, words ending here) make prefix counting and deletion O(L).
- Serialize a binary tree in preorder with a null marker such as "#", and deserialize by reading it back in the same order.
Common pitfalls
- Mixing up search (a whole word) and startsWith (a prefix) by not checking the end-of-word marker.
- A fixed 26-way array assumes lowercase letters; use a hash map of children for uppercase, digits or Unicode.
- Serializing without separators makes multi-digit and negative values impossible to parse back.
class Trie:
def __init__(self):
self.children: dict[str, Trie] = {}
self.prefix = 0
self.words = 0
def insert(self, word: str) -> None:
node = self
for ch in word:
node = node.children.setdefault(ch, Trie())
node.prefix += 1
node.words += 1
def _walk(self, s: str):
node = self
for ch in s:
node = node.children.get(ch)
if node is None:
return None
return node
def count_word(self, word: str) -> int:
node = self._walk(word)
return node.words if node else 0
def count_prefix(self, prefix: str) -> int:
node = self._walk(prefix)
return node.prefix if node else 0
35 Practical Bit Operations and Numeric Boundaries 实用位运算与数值边界
Bit tricks and fast power · O(log n)
Key points
- x & (x-1) clears the lowest set bit and x & -x isolates it; XOR satisfies a ^ a = 0, which finds the element that appears once.
- Fast power splits the exponent into bits: square the base every round and multiply it into the result when the bit is 1, O(log exp).
- A set of up to 20 items fits in an integer mask; for (s = mask; s; s = (s-1) & mask) enumerates every non-empty submask.
Common pitfalls
- Multiplying two values near 10^9 overflows 32 bits; widen to long / long long before the modular multiply.
- Java's >> keeps the sign, so use >>> for negatives; Python ints are unbounded, so mask negatives with & 0xFFFFFFFF first.
- In C++ bitwise operators bind looser than comparisons, so x & 1 == 0 means x & (1 == 0); add parentheses (Java refuses to compile it).
def popcount(x: int) -> int:
"""Set bits in a non-negative x (int.bit_count() in Python 3.10+)."""
count = 0
while x:
x &= x - 1
count += 1
return count
def pow_mod(base: int, exp: int, mod: int) -> int:
"""base ** exp % mod by repeated squaring (the built-in pow(base, exp, mod) does the same)."""
result, base = 1 % mod, base % mod
while exp:
if exp & 1:
result = result * base % mod
base = base * base % mod
exp >>= 1
return result