cswork / templatesOpen the Line 500 list

LINE 500 · 35 STOPS · PYTHON

Template handbook: Python

One section per stop: the pattern, its complexity, three key points, three pitfalls and the Python template. Every template is compiled, run and checked against test data. Each group starts on a new page; choose “Save as PDF” in the print dialog to keep a file.

cswork.org/topics

Read/write pointers for in-place compaction · O(n) time · O(1) space

Key points

  1. Everything left of the write pointer w is final; the read pointer only scans forward, so each pointer moves once.
  2. Decide whether to keep a value by comparing it with nums[w-k], the kept result, not with the previous raw element.
  3. 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  # nums[:w] is the kept prefix
    for x in nums:
        if w < k or nums[w - k] != x:
            nums[w] = x
            w += 1
    return w

One-pass hash map lookup · O(n) time · O(n) space

Key points

  1. Query the complement before storing the current value: one pass finds earlier partners and never pairs an element with itself.
  2. Store what the question needs: an index for positions, a count for how many, and the first index only when you need the earliest.
  3. 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] = {}  # value -> index of an earlier element
    for i, x in enumerate(nums):
        if target - x in seen:  # look up before inserting: no self-pairing
            return seen[target - x], i
        seen[x] = i
    return -1, -1

KMP prefix function · O(n + m) time · O(m) space

Key points

  1. 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.
  2. Building pi and scanning the text are the same loop: building the table is the pattern matching against itself.
  3. 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  # pi[i]: longest proper prefix of pat[:i+1] that is also its suffix
    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]  # keep going: matches may overlap
    return res

Variable-size sliding window · O(n) time · O(Σ) space

Key points

  1. 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).
  2. For the longest window, update the answer after shrinking; for the shortest, update it inside the shrink loop while the window is still valid.
  3. 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)  # counts inside the window s[left:right+1]
    left = best = 0
    for right, c in enumerate(s):
        cnt[c] += 1
        while cnt[c] > 1:  # shrink until the window is valid again
            cnt[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Prefix sums with a hash count · O(n) time · O(n) space

Key points

  1. 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.
  2. When counting subarrays that sum to k, seed the map with {0: 1} for subarrays that start at index 0.
  3. 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}  # prefix sum -> occurrences; the empty prefix counts once
    pre = ans = 0
    for x in nums:
        pre += x
        ans += seen.get(pre - k, 0)  # sum(j..i) = pre_i - pre_j
        seen[pre] = seen.get(pre, 0) + 1
    return ans

Monotonic stack: next greater element · O(n) time · O(n) space

Key points

  1. Keep indexes on the stack, not values: you can still read the value and also measure distances such as days until a warmer day.
  2. Each element is pushed and popped once, so the nested while is still O(n) overall.
  3. 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 = []  # indexes still waiting; their values decrease from bottom to top
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            ans[stack.pop()] = x
        stack.append(i)
    return ans

Sort by end time, keep what fits · O(n log n) time

Key points

  1. 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.
  2. Minimum removals = total minus the maximum kept; "minimum arrows" is the same loop, except that touching endpoints count as overlapping.
  3. 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:  # fits after the last kept interval
            count += 1
            end = finish
    return count

Reverse in place, fast and slow pointers · O(n) time · O(1) space

Key points

  1. Save next before rewiring. Reversal is three moves: save next, point back, step forward.
  2. When the head may be removed or replaced, start from a dummy node that points at head and return dummy.next.
  3. 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  # save it before rewiring
        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

Level-order BFS · O(n) time · O(width) space

Key points

  1. Record the queue length at the start of each round; processing exactly that many nodes separates one level from the next.
  2. Before writing a recursive DFS, decide what a subtree returns (depth, balance, size); the answer is always a merge of left and right.
  3. 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)):  # exactly the nodes of this level
            node = q.popleft()
            level.append(node.val)
            for child in (node.left, node.right):
                if child:
                    q.append(child)
        levels.append(level)
    return levels

Return the one-sided gain, record the bent path globally · O(n) time · O(h) stack

Key points

  1. The recursion returns the best one-sided downward path, because a path that continues upward can use only one child.
  2. The path that bends at the node (left + node + right) only updates the global answer; it is never returned to the parent.
  3. 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:  # best downward path sum that starts at node
        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)  # the path that bends at node
        return node.val + max(left, right)  # only one side can continue upward

    gain(root)
    return best

Preorder picks the root, inorder splits the sides · O(n) time · O(n) space

Key points

  1. 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.
  2. A value-to-inorder-index map makes each split O(1) and the whole build O(n).
  3. 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)}  # value -> inorder index: O(1) splits
    roots = iter(preorder)  # preorder yields roots in exactly the order we build them

    def build(lo: int, hi: int):  # the subtree whose inorder range is [lo, hi)
        if lo == hi:
            return None
        root = TreeNode(next(roots))
        mid = pos[root.val]
        root.left = build(lo, mid)  # left before right, matching preorder
        root.right = build(mid + 1, hi)
        return root

    return build(0, len(inorder))

Iterative inorder walks a BST in sorted order · O(h + k) time · O(h) space

Key points

  1. An inorder walk of a BST is sorted, so k-th smallest, validation and predecessor/successor all become inorder problems.
  2. To validate a BST, pass (lo, hi) bounds down; every node must sit strictly inside the range its ancestors allow.
  3. 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:  # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()  # the next value in sorted order
        k -= 1
        if k == 0:
            return node.val
        node = node.right

Multi-source BFS, one ring per step · O(rows × cols)

Key points

  1. Enqueue every source at the start, as if from one virtual super source; the BFS layer is the shortest distance.
  2. Mark a cell visited when it is enqueued, so it is never added twice.
  3. 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)):  # every rotten cell spreads one step this minute
            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  # mark when enqueued, not when popped
                    fresh -= 1
                    q.append((nr, nc))
    return -1 if fresh else minutes

Union-find with path compression and union by size · ≈ O(α(n)) per operation

Key points

  1. Compress paths in find and hang the smaller tree under the larger in union; together each operation is close to constant time.
  2. union returning false means the two ends were already connected, which is how you detect cycles and redundant edges.
  3. 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  # number of components

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            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  # already connected: this edge would close a cycle
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a  # hang the smaller tree under the larger
        self.size[a] += self.size[b]
        self.count -= 1
        return True

Kahn's algorithm: dequeue zero in-degree nodes · O(V + E)

Key points

  1. A node with in-degree 0 has no unfinished prerequisites; place it, then decrement the in-degree of everything it points to.
  2. If fewer than n nodes come out, the rest sit on a cycle; that is the whole check for course-schedule problems.
  3. 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:  # every prerequisite of v is placed
                q.append(v)
    return order if len(order) == n else []

Dijkstra with a heap and lazy deletion · O((V + E) log V)

Key points

  1. The node popped with the smallest tentative distance is final; this only holds when every edge weight is non-negative.
  2. Skip decrease-key: push the new distance and, on pop, discard entries larger than dist (lazy deletion).
  3. 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  # stale entry: u was settled with a shorter distance
        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]

Kruskal: sort the edges, join with union-find · O(E log E)

Key points

  1. 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).
  2. n-1 chosen edges form a spanning tree; fewer than that means the graph is disconnected.
  3. 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:  # the lightest edge joining two different components
            parent[ru] = rv
            total += w
            used += 1
    return total if used == n - 1 else -1

Choose, recurse, undo; skip duplicates on the same level · O(n · 2^n)

Key points

  1. The template is three moves: choose, recurse, undo. path is a single buffer shared by the whole search.
  2. 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.
  3. 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)  # equal values become neighbours
    res, path = [], []

    def dfs(start: int) -> None:
        res.append(path[:])  # copy: path keeps changing
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue  # this value was already tried at this level
            path.append(nums[i])
            dfs(i + 1)
            path.pop()  # undo the choice

    dfs(0)
    return res

Backtrack over cut points with a palindrome table · O(n · 2^n)

Key points

  1. Each level decides where the next piece ends; when start reaches n you have one complete split.
  2. Precompute an O(n²) table of which substrings are palindromes so each check inside the search is O(1).
  3. 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)]  # pal[i][j]: s[i..j] is a palindrome
    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):  # the next piece is s[start..end]
            if pal[start][end]:
                path.append(s[start : end + 1])
                dfs(end + 1)
                path.pop()

    dfs(0)
    return res

N-Queens: prune by column and both diagonals · O(n!) worst case

Key points

  1. 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.
  2. Prune as early as possible: test for conflicts before recursing, not after the board is full.
  3. 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  # shift r - c into 0..2n-2
            if cols[c] or diag[d] or anti[r + c]:
                continue  # attacked: prune this branch
            cols[c] = diag[d] = anti[r + c] = True
            count += place(r + 1)
            cols[c] = diag[d] = anti[r + c] = False  # undo
        return count

    return place(0)

1-D DP with rolling variables · O(n) time · O(1) space

Key points

  1. 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.
  2. Derive the transition from the last decision: take element i or not, last jump of 1 step or 2.
  3. 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  # best totals up to i-2 and up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)  # skip x, or take it after i-2
    return prev1

Grid DP compressed to one row · O(rows × cols) time · O(cols) space

Key points

  1. 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".
  2. The first row and column have a single source; handle them separately or use an infinity sentinel.
  3. 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  # before row r is filled, dp[c] holds row r-1
    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]  # from above (old dp[c]) or the left (new dp[c-1])
    return dp[-1]

0/1 knapsack backwards, unbounded forwards · O(n × target)

Key points

  1. 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.
  2. Items outside and capacity inside counts combinations (order ignored); capacity outside and items inside counts permutations.
  3. 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  # dp[s]: ways to reach sum s
    for x in nums:
        for s in range(target, x - 1, -1):  # backwards: x is used at most once
            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:  # coins outside: each multiset is counted once
        for s in range(coin, amount + 1):  # forwards: a coin may be reused
            dp[s] += dp[s - coin]
    return dp[amount]

LIS with a tails array and binary search · O(n log n)

Key points

  1. 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.
  2. Strictly increasing uses lower_bound (first ≥ x); non-decreasing uses upper_bound (first > x).
  3. 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 = []  # tails[k]: smallest tail of an increasing subsequence of length k+1
    for x in nums:
        i = bisect_left(tails, x)  # bisect_right for non-decreasing
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)

Two-string DP over prefixes · O(m × n)

Key points

  1. 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.
  2. If the last characters match, inherit dp[i-1][j-1]; otherwise replace, delete and insert map to the diagonal, upper and left cells.
  3. 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[i][j]: edits to turn a[:i] into b[:j]; row 0 and column 0 are the empty prefixes
    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:  # replace, delete from a, insert into a
                dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]

Interval DP with the left end running backwards · O(n²)

Key points

  1. dp[i][j] depends only on shorter ranges, dp[i+1][*] and dp[*][j-1], so fill i backwards and j forwards.
  2. If the two ends match, shrink inward and add 2; otherwise drop one end and keep the better of the two.
  3. 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)]  # dp[i][j]: answer for s[i..j]
    for i in range(n - 1, -1, -1):  # i backwards so dp[i+1][*] is ready
        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

Ending-at-i states: track both max and min · O(n) time · O(1) space

Key points

  1. Define the state as "ending at i"; a contiguous subarray then has two transitions: extend the previous run or restart at i.
  2. A negative factor turns the maximum into the minimum, so keep both a max state and a min state.
  3. 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]  # max and min product of a subarray ending here
    for x in nums[1:]:
        cand = (x, hi * x, lo * x)  # restart, or extend; a negative x swaps max and min
        hi, lo = max(cand), min(cand)
        best = max(best, hi)
    return best

Three states: holding, cooling down, free · O(n) time · O(1) space

Key points

  1. 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.
  2. All of today's values must come from yesterday's, so assign them simultaneously or through temporaries.
  3. 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  # profit at the end of a day in each state
    for p in prices:
        hold, cool, free = (
            max(hold, free - p),  # keep holding, or buy today (only from free)
            hold + p,  # sell today
            max(free, cool),  # rest
        )
    return max(cool, free)

Sort by end, binary search the last compatible job · O(n log n)

Key points

  1. 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.
  2. Find the last compatible job by binary searching the end times, for O(n log n) overall.
  3. "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)  # dp[i]: best using the first i jobs by end time
    for i, (_, s, p) in enumerate(jobs):
        k = bisect_right(ends, s, 0, i)  # jobs[:k] all end by time s
        dp[i + 1] = max(dp[i], dp[k] + p)  # skip job i, or take it after jobs[:k]
    return dp[-1]

Tree DP: each node returns (take, skip) · O(n)

Key points

  1. Tree DP runs post-order: get both children's results first, then compute the current node, returning a small tuple.
  2. 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.
  3. 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]:  # (best if node is taken, best if it is not)
        if not node:
            return 0, 0
        lt, ls = dfs(node.left)
        rt, rs = dfs(node.right)
        take = node.val + ls + rs  # children must be skipped
        skip = max(lt, ls) + max(rt, rs)  # children are free to choose
        return take, skip

    return max(dfs(root))

Lazy iterator: hasNext does the advancing · O(1) amortised per call

Key points

  1. 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.
  2. Keep only positions (row and column) instead of copying every element into one big array in the constructor.
  3. 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  # skip finished and empty rows
        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]

LRU: hash map plus doubly linked list · O(1) get and put

Key points

  1. 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).
  2. 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.
  3. 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()  # a hash map over a doubly linked list; the end is most recent

    def get(self, key: int) -> int:
        if key not in self.data:
            return -1
        self.data.move_to_end(key)  # mark as most recently used
        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)  # evict the least recently used

Trie nodes hold children and counts · O(length) per operation

Key points

  1. Each node is a prefix; insert and lookup walk down one character at a time, so the cost depends only on the word length.
  2. Counts on the nodes (words passing through, words ending here) make prefix counting and deletion O(L).
  3. 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  # words passing through this node
        self.words = 0  # words ending exactly here

    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

Bit tricks and fast power · O(log n)

Key points

  1. 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.
  2. 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).
  3. 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  # clear the lowest set bit
        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