A complete practice system
Learn the patterns.
Earn the transfer.
Build transferable DSA interview skill through representative problems, deliberate variations, retention, and mixed practice.
Three passes. A deliberate order.
Coverage before repetition; transfer after familiarity.Follow the numbered curriculum within each pass and check its prerequisites. Stages organize the concepts; tiers set depth. Completing every pattern includes the Extension pass.
Learn the foundational methods and their main interview applications. Work in curriculum order; write a proof idea and complexity before coding.
Solve variations that expose missing conditions and combine patterns. Start mixing topics and hiding the method labels.
Complete all 72-pattern coverage, including specialist strings, digit/bitmask DP, range structures, and graph algorithms. Prioritize these after the general interview path unless your target role requires them.
Start here: Choose Core below. Before opening a learning note, try to explain which property permits a faster solution. Save the blind checkpoint problems for a mixed session and use the spreadsheet to record attempts, retention, and review dates.
The problem curriculum
Official links · assigned approaches · prerequisitesLearning notes start closed. Solve the problem first, then check the assigned approach: an accepted alternative may be correct without exercising the intended pattern. Problem numbering is stable across this reference and the tracker.
Reveal learning notes #01
- What this teaches
- Translate a pair constraint into a complement lookup while preserving distinct indices.
- Target approach
- One-pass value-to-index map; query before insertion.
- Pattern coverage
- #01 Hash lookup and frequency
Reveal learning notes #01
- What this teaches
- Design a canonical key that identifies an entire equivalence class.
- Target approach
- Map a fixed-alphabet character-count tuple to its group; discuss sorted-string keys.
- Pattern coverage
- #01 Hash lookup and frequency
- Build on
- Two Sum
Reveal learning notes #03
- What this teaches
- Separate the unread suffix from the compacted valid prefix.
- Target approach
- Stable read/write compaction; return the logical prefix length.
- Pattern coverage
- #03 Read-write pointers
Reveal learning notes #07
- What this teaches
- Answer static range queries through an identity prefix and an inverse aggregate.
- Target approach
- Build prefix[0]=0 and answer inclusive queries with prefix[right+1]-prefix[left].
- Pattern coverage
- #07 Prefix aggregates
Reveal learning notes #01, #08
- What this teaches
- Count earlier prefix states rather than attempting a sum window that fails with negatives.
- Target approach
- Seed frequency[0]=1; query prefix-k before recording the current prefix.
- Pattern coverage
- #01 Hash lookup and frequency; #08 Prefix sum plus hash map
- Build on
- Range Sum Query - Immutable; Two Sum
Reveal learning notes #09
- What this teaches
- Represent each offline range increment by two endpoint changes.
- Target approach
- Apply inclusive booking updates to a difference array, then reconstruct with a prefix sum.
- Pattern coverage
- #09 Difference array
Reveal learning notes #10
- What this teaches
- Define the best nonempty subarray ending exactly at the current index.
- Target approach
- Kadane recurrence initialized from the first value; include an all-negative test.
- Pattern coverage
- #10 Kadane's maximum subarray
Reveal learning notes #11
- What this teaches
- Compose summaries from both sides without division, including zero-valued inputs.
- Target approach
- Write prefix products into output, then multiply by a running suffix product.
- Pattern coverage
- #11 Prefix-suffix composition
Reveal learning notes Additional foundation
- What this teaches
- Derive the coordinate transformation and preserve unread values during an in-place permutation.
- Target approach
- Transpose then reverse rows, or rotate four-cell cycles; use O(1) auxiliary space.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Reveal learning notes Additional foundation
- What this teaches
- Maintain shrinking boundaries and guard single remaining rows or columns.
- Target approach
- Four boundaries with explicit termination guards; output space excluded from auxiliary space.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Rotate Image
Reveal learning notes Additional foundation
- What this teaches
- Reuse input storage as markers without confusing original values with newly written state.
- Target approach
- Use first row and column as markers plus separate flags; O(1) auxiliary space.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Rotate Image
Reveal learning notes #70
- What this teaches
- Implement the divide, merge, and complexity argument behind a standard O(n log n) comparison sort.
- Target approach
- Implement merge sort without a library sort; later compare randomized quicksort and its worst case.
- Pattern coverage
- #70 Merge-sort counting / divide and conquer
Reveal learning notes #01
- What this teaches
- Use equality membership as the simplest hash-set invariant.
- Target approach
- Insert into a set and detect an existing value; compare expected linear time with sorting.
- Pattern coverage
- #01 Hash lookup and frequency
Reveal learning notes #01
- What this teaches
- Encode row, column, and sub-box uniqueness constraints separately.
- Target approach
- Sets or masks for each row, column, and box; validate a board rather than solve it.
- Pattern coverage
- #01 Hash lookup and frequency
- Build on
- Contains Duplicate
Reveal learning notes #03
- What this teaches
- Compact retained values stably while keeping an explicit write boundary.
- Target approach
- Read-write pointers in O(n) time and O(1) extra space.
- Pattern coverage
- #03 Read-write pointers
Reveal learning notes #03
- What this teaches
- Generalize compaction to three regions while preserving an explicit unknown region. Maintain three resolved regions while an unknown region shrinks.
- Target approach
- Dutch national flag partition with low, scan, and high boundaries; do not advance scan after every swap. Additional focus: Dutch national flag partition in one pass with O(1) auxiliary space.
- Pattern coverage
- #03 Read-write pointers
Reveal learning notes #02
- What this teaches
- Use sorted order to justify discarding one endpoint after every comparison.
- Target approach
- Opposite-end pointers with an explicit argument for the chosen move.
- Pattern coverage
- #02 Opposite-end two pointers
Reveal learning notes #02
- What this teaches
- Reduce a three-value search to a sorted pair scan without duplicate output.
- Target approach
- Sort; fix one value; use two pointers and deliberate duplicate skipping.
- Pattern coverage
- #02 Opposite-end two pointers
Reveal learning notes #02
- What this teaches
- Prove endpoint elimination using a bottleneck rather than a target sum.
- Target approach
- Move the shorter boundary because retaining it while shrinking width cannot improve the area.
- Pattern coverage
- #02 Opposite-end two pointers
Reveal learning notes #04
- What this teaches
- Update a fixed-length aggregate in constant time by exchanging its two boundary contributions.
- Target approach
- Initialize exactly k elements, then subtract outgoing and add incoming values.
- Pattern coverage
- #04 Fixed-size sliding window
Reveal learning notes #01, #04
- What this teaches
- Replace a scalar window sum with a multiplicity-sensitive character signature.
- Target approach
- Fixed window of len(s1) with frequency differences or matched-count bookkeeping.
- Pattern coverage
- #01 Hash lookup and frequency; #04 Fixed-size sliding window
- Build on
- Maximum Average Subarray I; Group Anagrams
Reveal learning notes #01, #05
- What this teaches
- Maintain a longest feasible window when a newly repeated value invalidates uniqueness.
- Target approach
- Frequency window or last-seen indices; advance left monotonically.
- Pattern coverage
- #01 Hash lookup and frequency; #05 Variable-size sliding window
- Build on
- Two Sum
Reveal learning notes #05
- What this teaches
- Use positive values to justify repeatedly shrinking a qualifying sum window.
- Target approach
- Expand right and shrink while sum meets the threshold; state why negatives invalidate this proof.
- Pattern coverage
- #05 Variable-size sliding window
Reveal learning notes #01, #05
- What this teaches
- Distinguish covering all required multiplicities from merely containing distinct required symbols.
- Target approach
- Track required counts and satisfied requirements; shrink repeatedly only while the complete multiset is covered.
- Pattern coverage
- #01 Hash lookup and frequency; #05 Variable-size sliding window
Reveal learning notes #01, #05, #06
- What this teaches
- Count every valid suffix and subtract adjacent at-most counts to obtain an exact count.
- Target approach
- Implement atMost(k)-atMost(k-1), returning zero for negative limits.
- Pattern coverage
- #01 Hash lookup and frequency; #05 Variable-size sliding window; #06 Exactly k via at-most counts
Reveal learning notes #12
- What this teaches
- Keep unresolved indices until a later value permanently resolves their next-greater boundary.
- Target approach
- Decreasing stack of indices; pop and compute index distances when a warmer day arrives.
- Pattern coverage
- #12 Monotonic stack
Reveal learning notes #12
- What this teaches
- Turn nearest-smaller boundaries into the maximum valid width for each bar.
- Target approach
- Monotonic stack with a flush sentinel and an explicit equal-height policy.
- Pattern coverage
- #12 Monotonic stack
- Build on
- Daily Temperatures
Reveal learning notes #13
- What this teaches
- Separate candidate domination at the back from index expiration at the front.
- Target approach
- Decreasing deque of indices; expire before reading the current window maximum.
- Pattern coverage
- #13 Monotonic deque
Reveal learning notes #14
- What this teaches
- Validate order and nesting by matching the most recent unmatched opening symbol.
- Target approach
- Stack with closing-to-opening mapping; reject mismatches and leftover openers.
- Pattern coverage
- #14 Stack for nested structure
Reveal learning notes #14
- What this teaches
- Evaluate completed subexpressions while preserving noncommutative operand order.
- Target approach
- Value stack; pop right operand before left and implement truncation toward zero.
- Pattern coverage
- #14 Stack for nested structure
Reveal learning notes #15
- What this teaches
- Implement a shrinking search interval whose endpoints and failure behavior are unambiguous.
- Target approach
- Iterative binary search with a documented closed or half-open interval invariant.
- Pattern coverage
- #15 Binary search for a boundary
Find First and Last Position of Element in Sorted Array (official problem, opens in a new tab)
Reveal learning notes #15
- What this teaches
- Distinguish finding any match from locating both equality boundaries.
- Target approach
- Implement lower_bound and upper_bound, deriving the final interval from their indices.
- Pattern coverage
- #15 Binary search for a boundary
- Build on
- Binary Search
Reveal learning notes #15
- What this teaches
- Use the sorted half of a rotated array to determine which side can contain the target.
- Target approach
- Maintain target containment and identify the sorted half at every step; explain how this extends ordinary boundary search.
- Pattern coverage
- #15 Binary search for a boundary
- Build on
- Binary Search
Reveal learning notes #15
- What this teaches
- Exploit global row-to-row ordering to search a matrix as one virtual sorted array.
- Target approach
- Binary search a flattened index and map it to row and column.
- Pattern coverage
- #15 Binary search for a boundary
- Build on
- Binary Search
Koko Eating Bananas (official problem, opens in a new tab)
Reveal learning notes #16
- What this teaches
- Turn minimum speed into a monotone time-feasibility predicate.
- Target approach
- Search the first speed whose summed ceiling-division hours fit h; use safe arithmetic.
- Pattern coverage
- #16 Binary search on the answer
- Build on
- Binary Search
Reveal learning notes #16
- What this teaches
- Prove a greedy feasibility check before searching the optimal maximum load.
- Target approach
- Binary search capacity between max(weights) and sum(weights); greedily pack consecutive packages per day.
- Pattern coverage
- #16 Binary search on the answer
- Build on
- Koko Eating Bananas
Reveal learning notes #17
- What this teaches
- Summarize sorted overlapping intervals by one current merged range.
- Target approach
- Sort by start; extend the current end or emit a completed range; state touching-endpoint semantics.
- Pattern coverage
- #17 Sort and merge intervals
Restaurant Customers (official problem, opens in a new tab)
Reveal learning notes #18
- What this teaches
- Replace continuous time with the finite set of arrivals and departures.
- Target approach
- Sort signed endpoint events and track the running maximum; the official task guarantees all times are distinct.
- Pattern coverage
- #18 Sweep line and events
Reveal learning notes #23
- What this teaches
- Detect repeated node identities without storing every visited node.
- Target approach
- Floyd slow/fast traversal with null checks; reason about relative motion in a cycle.
- Pattern coverage
- #23 Fast-slow pointers
Reveal learning notes #24
- What this teaches
- Reverse links while keeping access to the unreversed suffix.
- Target approach
- Iterative previous/current/next pointer reversal; preserve the next node before redirecting the link.
- Pattern coverage
- #24 Linked-list reversal
Reveal learning notes Additional foundation
- What this teaches
- Merge through node identities and preserve both input continuations while rewiring links.
- Target approach
- Dummy-head iterative merge of two sorted lists, followed by attaching the remaining tail.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Reveal learning notes #23, #24
- What this teaches
- Compose midpoint detection, reversal, and alternating merge without introducing a cycle.
- Target approach
- Find the middle, split the list, reverse the second half, and weave nodes in place.
- Pattern coverage
- #23 Fast-slow pointers; #24 Linked-list reversal
Reveal learning notes Additional foundation
- What this teaches
- Use a fixed pointer gap to turn distance from the tail into one forward traversal.
- Target approach
- Dummy head and two pointers separated by n nodes; unlink the target through its predecessor.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Reveal learning notes #71
- What this teaches
- Constant-time lookup and recency order require a hash map and a directly unlinkable ordered structure.
- Target approach
- Implement a hash map to doubly linked nodes plus sentinel head/tail; maintain map/list consistency on get, overwrite, insertion, and eviction.
- Pattern coverage
- #71 Composite structures for operation guarantees
Reveal learning notes #71
- What this teaches
- Constant-time uniform sampling needs dense random-access storage, so deletion swaps with the final element.
- Target approach
- Combine a dynamic array with a value-to-index map, perform swap-and-pop deletion, and sample an array index uniformly.
- Pattern coverage
- #71 Composite structures for operation guarantees
Reveal learning notes #14, #71
- What this teaches
- Maintain a second invariant so minimum queries remain constant-time under pops.
- Target approach
- Stack plus per-level minimum, or a synchronized minimum stack.
- Pattern coverage
- #14 Stack for nested structure; #71 Composite structures for operation guarantees
- Build on
- Valid Parentheses
Reveal learning notes #71
- What this teaches
- Distinguish amortized cost from the cost of one transfer operation.
- Target approach
- Two stacks; transfer only when the output stack is empty. Prove amortized O(1) operations.
- Pattern coverage
- #71 Composite structures for operation guarantees
- Build on
- Valid Parentheses
Reveal learning notes Additional foundation
- What this teaches
- Propagate arithmetic carry through unequal-length lists and a possible final node.
- Target approach
- Iterative digit addition using a dummy head and carry; account for output space.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Merge Two Sorted Lists
Reveal learning notes #19, #22
- What this teaches
- Compare a bounded heap against in-place rank selection without confusing selection with sorting.
- Target approach
- Implement both a size-k min-heap and randomized three-way quickselect; explain their separate worst-case guarantees.
- Pattern coverage
- #19 Heap for top k; #22 Quickselect
Reveal learning notes #01, #19
- What this teaches
- Separate frequency aggregation from selecting the most frequent distinct keys.
- Target approach
- Count frequencies, then retain a heap of k entries; discuss a bucket alternative after the target solution.
- Pattern coverage
- #01 Hash lookup and frequency; #19 Heap for top k
- Build on
- Two Sum; Kth Largest Element in an Array
Reveal learning notes #19
- What this teaches
- Preserve only the necessary order statistic across a stream of state-changing calls.
- Target approach
- Maintain a min-heap capped at k and return its root after each insertion.
- Pattern coverage
- #19 Heap for top k
- Build on
- Kth Largest Element in an Array
Reveal learning notes #20
- What this teaches
- Expose only one candidate per sorted source instead of heapifying every node.
- Target approach
- Min-heap of list heads with safe tie-breaking; pop a node and push its successor.
- Pattern coverage
- #20 Heap for k-way merge
- Build on
- Merge Two Sorted Lists
Reveal learning notes #21
- What this teaches
- Maintain both ordering and size-balance invariants across two priority queues.
- Target approach
- Lower max-heap and upper min-heap; rebalance after insertions and query their roots.
- Pattern coverage
- #21 Two heaps for a median
Reveal learning notes #50
- What this teaches
- Keeping the greatest number of compatible intervals is equivalent to deleting the fewest intervals.
- Target approach
- Sort by end time and retain each compatible interval; give an exchange argument for choosing the earliest finishing interval.
- Pattern coverage
- #50 Greedy choice with an exchange proof
Reveal learning notes #50
- What this teaches
- Reachability can be summarized by the farthest reachable index instead of recording every path.
- Target approach
- Maintain the farthest reachable boundary and fail exactly when the next index lies beyond it.
- Pattern coverage
- #50 Greedy choice with an exchange proof
Reveal learning notes #50
- What this teaches
- Minimum jumps needs layer boundaries in addition to a farthest-reach invariant.
- Target approach
- Scan the current reachable layer, accumulate the next farthest boundary, and increment jumps only when the current layer ends.
- Pattern coverage
- #50 Greedy choice with an exchange proof
- Build on
- Jump Game
Partition Labels (official problem, opens in a new tab)
Reveal learning notes #50
- What this teaches
- The last occurrence of every included symbol forces the earliest possible end of a valid partition.
- Target approach
- Precompute last occurrences and extend a partition boundary until the scan reaches the maximum forced endpoint.
- Pattern coverage
- #50 Greedy choice with an exchange proof
Room Allocation (official problem, opens in a new tab)
Reveal learning notes #51
- What this teaches
- Assigning every booking to a room minimizes resources, unlike selecting a subset of bookings.
- Target approach
- Sort arrivals and use a min-heap of (departure, room ID); reuse only when departure < arrival because occupied booking endpoints are inclusive.
- Pattern coverage
- #51 Greedy scheduling with a heap
- Build on
- Non-overlapping Intervals
Reveal learning notes #51
- What this teaches
- When only one event can be attended per day, the soonest-expiring currently available event is the safest choice.
- Target approach
- Sweep days, add newly available events to a minimum-end-day heap, discard expired events, and attend one event per day; jump over empty periods.
- Pattern coverage
- #51 Greedy scheduling with a heap
- Build on
- Non-overlapping Intervals
Reveal learning notes #26
- What this teaches
- A queue frontier separates nodes by depth even when the tree is unbalanced.
- Target approach
- BFS with a fixed current-level queue length.
- Pattern coverage
- #26 BFS / multi-source BFS
Reveal learning notes #36
- What this teaches
- Define a recursive return contract and derive a parent result from child results.
- Target approach
- Postorder DFS with an empty-tree base case; also write iterative DFS.
- Pattern coverage
- #36 Tree postorder DP
Reveal learning notes #25
- What this teaches
- Reason about an in-place recursive transformation without losing references to children.
- Target approach
- DFS or BFS swapping child pointers, with an explicit iterative version.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #25
- What this teaches
- Traverse pairs of nodes and treat null structure as part of equality.
- Target approach
- Paired DFS with asymmetric-null and unequal-value rejection.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #36
- What this teaches
- Return a failure sentinel with height so each subtree is analyzed once.
- Target approach
- One postorder pass returning height or an unbalanced sentinel.
- Pattern coverage
- #36 Tree postorder DP
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #36
- What this teaches
- Separate the one-branch height returned upward from a two-branch completed path.
- Target approach
- Postorder height computation plus a global or returned best diameter.
- Pattern coverage
- #36 Tree postorder DP
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #36
- What this teaches
- A negative child contribution may be omitted, while an all-negative tree still needs one node.
- Target approach
- Postorder maximum downward gain with a separately maintained completed path.
- Pattern coverage
- #36 Tree postorder DP
- Build on
- Diameter of Binary Tree
Reveal learning notes #37
- What this teaches
- A node must satisfy all ancestor bounds, not just its immediate parent comparison.
- Target approach
- Inherited-bound DFS and a strictly increasing inorder cross-check.
- Pattern coverage
- #37 BST ordering / inorder traversal
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #37
- What this teaches
- Inorder traversal streams sorted keys and can stop when the requested rank is reached.
- Target approach
- Iterative inorder traversal with an explicit stack.
- Pattern coverage
- #37 BST ordering / inorder traversal
- Build on
- Validate Binary Search Tree
Construct Binary Tree from Preorder and Inorder Traversal (official problem, opens in a new tab)
Reveal learning notes #25
- What this teaches
- Use the preorder root to split an inorder interval into the exact two subproblems.
- Target approach
- Recursive index ranges with an inorder position map; avoid repeated array slicing.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes #25, #26
- What this teaches
- A reversible encoding must preserve missing children as well as node values.
- Target approach
- Preorder with null tokens and a consuming parser, or equivalent level-order encoding.
- Pattern coverage
- #25 DFS / flood fill; #26 BFS / multi-source BFS
Reveal learning notes #38
- What this teaches
- Combine subtree evidence and allow one target to be an ancestor of the other.
- Target approach
- Single-query postorder DFS with explicit return semantics.
- Pattern coverage
- #38 LCA / binary lifting
- Build on
- Maximum Depth of Binary Tree
Reveal learning notes Additional foundation
- What this teaches
- Understand left-node-right traversal and its explicit-stack state.
- Target approach
- Implement both recursive and iterative inorder traversal of a general binary tree.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Reveal learning notes #25
- What this teaches
- Distinguish root-to-leaf paths from paths allowed to stop at any node.
- Target approach
- DFS carrying a remaining target or running sum; accept only at a leaf.
- Pattern coverage
- #25 DFS / flood fill
Reveal learning notes #25
- What this teaches
- Start one traversal per unseen component and mark vertices on discovery.
- Target approach
- Iterative DFS and BFS flood fill; explain O(rows × columns) total work.
- Pattern coverage
- #25 DFS / flood fill
Reveal learning notes #25
- What this teaches
- Separate node identity from node value and cache each clone before visiting its neighbors.
- Target approach
- DFS or BFS with an original-node to cloned-node map.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Number of Islands
Reveal learning notes #25
- What this teaches
- Reverse the question by preserving every region connected to a boundary.
- Target approach
- Boundary-seeded flood fill followed by a board sweep.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Number of Islands
Pacific Atlantic Water Flow (official problem, opens in a new tab)
Reveal learning notes #25, #68
- What this teaches
- Reverse directed movement and intersect two independently reachable sets. Searching backward from each destination boundary replaces a separate downhill search from every cell.
- Target approach
- Two reverse flood fills from the ocean boundaries. Additional focus: Run two reverse flood fills from the ocean boundaries along nondecreasing heights and intersect the reachable sets.
- Pattern coverage
- #25 DFS / flood fill; #68 Reverse reasoning / reverse graph
- Build on
- Surrounded Regions
Reveal learning notes #26
- What this teaches
- Model simultaneous spread by enqueuing every initial source at time zero.
- Target approach
- Multi-source BFS with level or distance tracking.
- Pattern coverage
- #26 BFS / multi-source BFS
Reveal learning notes #26
- What this teaches
- Build an implicit unweighted graph without confusing a word transformation with string DP.
- Target approach
- BFS with wildcard buckets or generated one-letter neighbors; then explain bidirectional BFS.
- Pattern coverage
- #26 BFS / multi-source BFS
- Build on
- Rotting Oranges
Reveal learning notes #28
- What this teaches
- Finalize a nonnegative shortest distance when its current minimum heap entry is removed.
- Target approach
- Dijkstra with an adjacency list, a min-heap, and stale-entry checks.
- Pattern coverage
- #28 Dijkstra's shortest paths
- Build on
- Rotting Oranges
Cheapest Flights Within K Stops (official problem, opens in a new tab)
Reveal learning notes #29
- What this teaches
- A stop limit makes edge count part of the state and requires previous-round snapshots.
- Target approach
- Bounded Bellman–Ford for at most k + 1 edges, copying distances between rounds.
- Pattern coverage
- #29 Bellman–Ford
- Build on
- Network Delay Time
Reveal learning notes #31, #35
- What this teaches
- Distinguish a node already seen from a node active on the current directed DFS path.
- Target approach
- Implement three-color DFS for cycle detection and explain the Kahn indegree alternative.
- Pattern coverage
- #31 Topological ordering / DAG DP; #35 DFS cycle states / strongly connected components
Reveal learning notes #31
- What this teaches
- Produce a dependency order and reject a graph when fewer than all vertices are processed.
- Target approach
- Kahn topological ordering with indegree updates.
- Pattern coverage
- #31 Topological ordering / DAG DP
- Build on
- Course Schedule
Reveal learning notes #32
- What this teaches
- An undirected edge closes a cycle exactly when its endpoints are already connected.
- Target approach
- DSU with path compression and union by size or rank.
- Pattern coverage
- #32 Union–find / disjoint-set union
Accounts Merge (official problem, opens in a new tab)
Reveal learning notes #32
- What this teaches
- Build components from shared identifiers while retaining original record metadata.
- Target approach
- DSU over accounts or emails, then collect and sort each component.
- Pattern coverage
- #32 Union–find / disjoint-set union
- Build on
- Redundant Connection
Reveal learning notes #32, #33
- What this teaches
- Minimizing total network cost differs from minimizing distance from one source.
- Target approach
- Kruskal with DSU; also implement dense O(n²) Prim to avoid storing all pairwise edges.
- Pattern coverage
- #32 Union–find / disjoint-set union; #33 Minimum spanning tree
- Build on
- Redundant Connection
Reveal learning notes #34
- What this teaches
- Opposite-group constraints require coloring every connected component and detecting equal-color edges.
- Target approach
- BFS or DFS two-coloring; explain the odd-cycle obstruction.
- Pattern coverage
- #34 Bipartite coloring
- Build on
- Number of Islands
Reveal learning notes #49
- What this teaches
- Independent include/exclude choices generate a power set; the output itself is exponential.
- Target approach
- Implement include/exclude DFS with one mutable path and copy only when recording an answer.
- Pattern coverage
- #49 Backtracking and pruning
Reveal learning notes #49
- What this teaches
- Permutations require tracking used positions, unlike increasing-index subset generation.
- Target approach
- Use choose/recurse/undo with a used array or in-place swapping; explain why each ordering appears once.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Subsets
Reveal learning notes #49
- What this teaches
- Unlimited reuse changes the next recursion index and permits target-based pruning only because values are positive.
- Target approach
- Sort candidates, recurse from a nondecreasing candidate index, allow reuse of that index, and prune when the candidate exceeds the remaining target.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Subsets
Reveal learning notes #49
- What this teaches
- A global validity requirement becomes a prefix invariant that rejects invalid branches early.
- Target approach
- Track opened and closed parentheses; add a closing parenthesis only while closed < opened and open at most n pairs.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Subsets
Reveal learning notes #53
- What this teaches
- Whole-word membership and prefix membership differ only at the terminal marker.
- Target approach
- Implement insert, search, and startsWith with explicit trie nodes and word-end flags.
- Pattern coverage
- #53 Trie / prefix tree
Reveal learning notes #53
- What this teaches
- A wildcard makes lookup branch into multiple trie children, so it is no longer always linear in word length.
- Target approach
- Implement trie insertion and DFS lookup that explores every existing child for a dot.
- Pattern coverage
- #53 Trie / prefix tree
- Build on
- Implement Trie (Prefix Tree)
Reveal learning notes #49
- What this teaches
- Undo per-path visited state without mixing different starting cells or branches.
- Target approach
- DFS choose-mark-explore-unmark; never reuse a cell within one word path.
- Pattern coverage
- #49 Backtracking and pruning
Reveal learning notes #31, #39
- What this teaches
- Strictly increasing transitions turn a seemingly cyclic grid into a DAG.
- Target approach
- Memoized DFS or topological DAG DP; cache the longest path beginning at each cell.
- Pattern coverage
- #31 Topological ordering / DAG DP; #39 Memoization / one-dimensional DP
- Build on
- Course Schedule II
Reveal learning notes #39
- What this teaches
- Choose a state, base cases, and recurrence before compressing memory.
- Target approach
- Memoized recursion, tabulation, then a two-value rolling recurrence.
- Pattern coverage
- #39 Memoization / one-dimensional DP
Reveal learning notes #39, #48
- What this teaches
- A prefix optimum must compare taking the current item with skipping it.
- Target approach
- Take/skip or prefix DP, then constant-space compression.
- Pattern coverage
- #39 Memoization / one-dimensional DP; #48 Finite-state DP: stock / cooldown
- Build on
- Climbing Stairs
Reveal learning notes #39, #48
- What this teaches
- A negative factor swaps the roles of the largest and smallest products ending at the previous position.
- Target approach
- Track both minimum and maximum products ending here, using previous-state snapshots and handling zero resets.
- Pattern coverage
- #39 Memoization / one-dimensional DP; #48 Finite-state DP: stock / cooldown
- Build on
- House Robber
Reveal learning notes #39
- What this teaches
- Zero and two-digit validity rules determine which prefix transitions exist.
- Target approach
- Prefix or suffix DP with explicit single-digit and double-digit guards.
- Pattern coverage
- #39 Memoization / one-dimensional DP
- Build on
- Climbing Stairs
Reveal learning notes #39
- What this teaches
- Segmenting a string is reachability between valid prefix boundaries.
- Target approach
- Boolean prefix DP or memoized suffix DP with dictionary lookup.
- Pattern coverage
- #39 Memoization / one-dimensional DP
- Build on
- Decode Ways
Reveal learning notes #40
- What this teaches
- Acyclic movement makes each cell depend only on already solved predecessors.
- Target approach
- Two-dimensional path-count DP, then row compression.
- Pattern coverage
- #40 Grid DP
- Build on
- Climbing Stairs
Reveal learning notes #40
- What this teaches
- The same grid dependency graph can optimize a cost instead of counting routes.
- Target approach
- Minimum-cost grid DP with valid unreachable-state initialization.
- Pattern coverage
- #40 Grid DP
- Build on
- Unique Paths
Reveal learning notes #40
- What this teaches
- A cell summarizes the largest valid structure ending there rather than a route to it.
- Target approach
- DP using one plus the minimum of left, up, and diagonal sizes.
- Pattern coverage
- #40 Grid DP
- Build on
- Minimum Path Sum
Reveal learning notes #41
- What this teaches
- Single-use items require descending sum updates in a compressed reachability table.
- Target approach
- 0/1 subset-sum DP to half the total after parity checking.
- Pattern coverage
- #41 0/1 knapsack / subset sum
- Build on
- Climbing Stairs
Target Sum (official problem, opens in a new tab)
Reveal learning notes #41
- What this teaches
- Convert sign choices to counting subsets while preserving parity, range, and zero multiplicity.
- Target approach
- Counting 0/1 knapsack after deriving the target subset sum, or equivalent signed-sum DP.
- Pattern coverage
- #41 0/1 knapsack / subset sum
- Build on
- Partition Equal Subset Sum
Reveal learning notes #42
- What this teaches
- Repeatable choices permit transitions from already reachable smaller amounts.
- Target approach
- Unbounded minimum-count DP with an impossible-state sentinel.
- Pattern coverage
- #42 Unbounded knapsack / coin change
- Build on
- Climbing Stairs
Reveal learning notes #42
- What this teaches
- Type-first iteration counts unordered combinations without counting their permutations.
- Target approach
- Unbounded counting DP with coins outside and increasing amounts inside.
- Pattern coverage
- #42 Unbounded knapsack / coin change
- Build on
- Coin Change
Reveal learning notes #43
- What this teaches
- Two prefix indices preserve which elements remain available in each sequence.
- Target approach
- Two-sequence DP with match and skip transitions; reconstruct one optimal subsequence.
- Pattern coverage
- #43 Two-sequence DP: LCS / edit distance
- Build on
- Climbing Stairs
Reveal learning notes #43
- What this teaches
- Each allowed edit changes one or both prefix indices with its own transition cost.
- Target approach
- Prefix DP over insert, delete, and replace with empty-prefix boundaries.
- Pattern coverage
- #43 Two-sequence DP: LCS / edit distance
- Build on
- Longest Common Subsequence
Reveal learning notes #44
- What this teaches
- A minimal tail per length dominates larger tails without preserving a complete answer sequence.
- Target approach
- First quadratic predecessor DP, then lower-bound tails; reconstruct using predecessor indices.
- Pattern coverage
- #44 Longest increasing subsequence: tails
- Build on
- Climbing Stairs
Reveal learning notes #45
- What this teaches
- Removing endpoints creates smaller intervals with a different recurrence from common-substring problems.
- Target approach
- Interval DP with matching-endpoint and skip-endpoint transitions.
- Pattern coverage
- #45 Interval DP
- Build on
- Longest Common Subsequence
Reveal learning notes #48
- What this teaches
- A cooldown changes the legal next actions and needs a distinct state or delayed transition.
- Target approach
- Holding, sold, and resting states updated from the previous day.
- Pattern coverage
- #48 Finite-state DP: stock / cooldown
- Build on
- House Robber
Reveal learning notes #54
- What this teaches
- A mismatch can reuse a matched border instead of restarting the text scan.
- Target approach
- Implement KMP prefix-function preprocessing and search from scratch; do not use a substring-search built-in.
- Pattern coverage
- #54 KMP / Z-function matching
Reveal learning notes #56
- What this teaches
- Contiguous palindromes are characterized by odd and even centers, unlike palindromic subsequences.
- Target approach
- Expand around every odd and even center and retain the longest interval.
- Pattern coverage
- #56 Palindrome centers / palindrome DP
Reveal learning notes #56
- What this teaches
- Counting all palindromic spans can reuse the truth value for the interval with both endpoints removed.
- Target approach
- Implement interval DP with length-one and length-two base cases and count all true intervals; then compare memory with center expansion.
- Pattern coverage
- #56 Palindrome centers / palindrome DP
- Build on
- Longest Palindromic Substring
Reveal learning notes #57
- What this teaches
- XOR cancellation works only because every other value has even multiplicity.
- Target approach
- XOR all values and explicitly use associativity, commutativity, and x XOR x = 0 in the explanation.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
Reveal learning notes #57
- What this teaches
- Clearing the lowest set bit counts only the bits that are present.
- Target approach
- Use n &= n - 1 until zero and state the input width assumptions.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
Reveal learning notes #57
- What this teaches
- Neighboring integers share a smaller bit-count subproblem.
- Target approach
- Derive and implement either bits[i] = bits[i >> 1] + (i & 1) or bits[i] = bits[i & (i - 1)] + 1.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
- Build on
- Number of 1 Bits
Reveal learning notes #58
- What this teaches
- String repetition compatibility must hold before a gcd of lengths identifies a common repeated block.
- Target approach
- Check that str1 + str2 equals str2 + str1, then compute the length with Euclid and return that prefix.
- Pattern coverage
- #58 GCD and modular arithmetic
Reveal learning notes #60
- What this teaches
- Point replacements plus range sums can be converted to additive updates and two prefix queries.
- Target approach
- Implement a Fenwick tree, keep old values to convert replacements to deltas, and compute sums by prefix subtraction.
- Pattern coverage
- #60 Fenwick tree / binary indexed tree
- Build on
- Range Sum Query - Immutable
Longest Consecutive Sequence (official problem, opens in a new tab)
Reveal learning notes #01
- What this teaches
- Avoid rescanning every chain by expanding only from values with no predecessor.
- Target approach
- Hash set plus run-start test; prove each distinct value is visited only a constant number of times.
- Pattern coverage
- #01 Hash lookup and frequency
- Build on
- Two Sum
Merge Sorted Array (official problem, opens in a new tab)
Reveal learning notes #03
- What this teaches
- Choose a backward write direction when forward writes would overwrite unread data.
- Target approach
- Merge from the largest remaining values into the last free output position.
- Pattern coverage
- #03 Read-write pointers
Range Sum Query 2D - Immutable (official problem, opens in a new tab)
Reveal learning notes #07
- What this teaches
- Extend one-dimensional prefixes using two-dimensional inclusion-exclusion.
- Target approach
- Build a padded 2D prefix table and use four corners per rectangle query.
- Pattern coverage
- #07 Prefix aggregates
- Build on
- Range Sum Query - Immutable
Contiguous Array (official problem, opens in a new tab)
Reveal learning notes #01, #08
- What this teaches
- Use earliest occurrences instead of frequencies when the objective changes from counting to longest length.
- Target approach
- Map 0 to -1 and 1 to +1; retain the first index of every balance, including the empty prefix.
- Pattern coverage
- #01 Hash lookup and frequency; #08 Prefix sum plus hash map
- Build on
- Subarray Sum Equals K
Subarray Sums Divisible by K (official problem, opens in a new tab)
Reveal learning notes #01, #08
- What this teaches
- Replace exact prefix sums by equivalence classes modulo k.
- Target approach
- Count matching normalized prefix remainders; handle the language-specific behavior of negative remainders.
- Pattern coverage
- #01 Hash lookup and frequency; #08 Prefix sum plus hash map
- Build on
- Subarray Sum Equals K
Maximum Sum Circular Subarray (official problem, opens in a new tab)
Reveal learning notes #10
- What this teaches
- Split circular optima into an ordinary segment or the complement of a minimum segment.
- Target approach
- Run maximum and minimum Kadane with the total sum; guard the all-negative case.
- Pattern coverage
- #10 Kadane's maximum subarray
- Build on
- Maximum Subarray
Reverse Pairs (official problem, opens in a new tab)
Reveal learning notes #70
- What this teaches
- The doubled-value inequality must be counted independently of the ordinary merge comparison.
- Target approach
- Use merge sort with a separate monotone cross-half counting pass for leftValue > 2 * rightValue and wide arithmetic.
- Pattern coverage
- #70 Merge-sort counting / divide and conquer
Game of Life (official problem, opens in a new tab)
Reveal learning notes #57
- What this teaches
- Update every cell simultaneously while retaining each neighbor's old state.
- Target approach
- Encode old and new states in separate bits, then commit in a second pass.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
- Build on
- Set Matrix Zeroes
First Missing Positive (official problem, opens in a new tab)
Reveal learning notes Additional foundation
- What this teaches
- Use the bounded useful value domain as an implicit index map without extra storage.
- Target approach
- Cyclic placement or sign marking; prove O(n) work and handle duplicates safely.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Sort Colors
Next Permutation (official problem, opens in a new tab)
Reveal learning notes Additional foundation
- What this teaches
- Derive a lexicographic successor by changing the rightmost possible pivot.
- Target approach
- Find the decreasing suffix, swap the pivot with its smallest larger successor, then reverse the suffix.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Sort Colors
Trapping Rain Water (official problem, opens in a new tab)
Reveal learning notes #02, #11
- What this teaches
- Recognize both an all-other-position decomposition and an equivalent constant-space boundary invariant.
- Target approach
- First implement prefix/suffix maxima; then derive the two-pointer running-maxima solution.
- Pattern coverage
- #02 Opposite-end two pointers; #11 Prefix-suffix composition
Reveal learning notes #01, #05
- What this teaches
- Express replacement feasibility as window length minus a dominant-character frequency.
- Target approach
- Maintain a count window and prove the chosen maximum-frequency bookkeeping, including any stale-maximum optimization.
- Pattern coverage
- #01 Hash lookup and frequency; #05 Variable-size sliding window
Max Consecutive Ones III (official problem, opens in a new tab)
Reveal learning notes #05
- What this teaches
- Convert allowed modifications into a window budget that is monotone under shrinking.
- Target approach
- Track zero count and shrink when it exceeds k.
- Pattern coverage
- #05 Variable-size sliding window
Count Number of Nice Subarrays (official problem, opens in a new tab)
Reveal learning notes #05, #06
- What this teaches
- Transfer the exactly-k identity from distinct values to a marked-element count.
- Target approach
- Treat odd numbers as marked; subtract two at-most counters and compare with a prefix-count alternative.
- Pattern coverage
- #05 Variable-size sliding window; #06 Exactly k via at-most counts
Sum of Subarray Minimums (official problem, opens in a new tab)
Reveal learning notes #12
- What this teaches
- Count each element's contribution while assigning duplicate minima to exactly one owner.
- Target approach
- Previous/next smaller spans with asymmetric strictness, then sum value*leftChoices*rightChoices.
- Pattern coverage
- #12 Monotonic stack
- Build on
- Largest Rectangle in Histogram
Remove K Digits (official problem, opens in a new tab)
Reveal learning notes #12
- What this teaches
- Combine a monotone stack with a limited removal budget and lexicographic optimality.
- Target approach
- Pop larger preceding digits while deletions remain; remove leftover suffix digits and normalize leading zeroes.
- Pattern coverage
- #12 Monotonic stack
- Build on
- Daily Temperatures
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (official problem, opens in a new tab)
Reveal learning notes #05, #13
- What this teaches
- Maintain both extrema while a variable-length window moves.
- Target approach
- One increasing and one decreasing deque; shrink until maximum-minus-minimum fits the limit.
- Pattern coverage
- #05 Variable-size sliding window; #13 Monotonic deque
Decode String (official problem, opens in a new tab)
Reveal learning notes #14
- What this teaches
- Suspend the current parse frame when entering nested repetition.
- Target approach
- Stack of repeat counts and accumulated parent fragments; account for decoded output size.
- Pattern coverage
- #14 Stack for nested structure
- Build on
- Valid Parentheses
Asteroid Collision (official problem, opens in a new tab)
Reveal learning notes #14
- What this teaches
- Resolve repeated adjacent interactions only when directions actually permit a collision.
- Target approach
- Stack of surviving asteroids; repeatedly resolve an incoming left-moving asteroid against positive stack tops.
- Pattern coverage
- #14 Stack for nested structure
- Build on
- Valid Parentheses
Car Pooling (official problem, opens in a new tab)
Reveal learning notes #09, #18
- What this teaches
- Model capacity with signed pickup/drop-off events and correct endpoint semantics.
- Target approach
- Use a coordinate difference array or sorted aggregated events; passengers leaving at a point release capacity there.
- Pattern coverage
- #09 Difference array; #18 Sweep line and events
- Build on
- Corporate Flight Bookings
Find Minimum in Rotated Sorted Array (official problem, opens in a new tab)
Reveal learning notes #15
- What this teaches
- Define a monotone comparison against a stable array endpoint to locate a rotation boundary.
- Target approach
- Find the first element at most the final value, using unique values and explicit handling of an unrotated array.
- Pattern coverage
- #15 Binary search for a boundary
- Build on
- Search in Rotated Sorted Array
Search in Rotated Sorted Array II (official problem, opens in a new tab)
Reveal learning notes #15
- What this teaches
- Recognize when duplicate endpoints hide the sorted-half information and force linear worst-case behavior.
- Target approach
- Rotated search with equal-boundary trimming; justify the degraded worst-case bound.
- Pattern coverage
- #15 Binary search for a boundary
- Build on
- Search in Rotated Sorted Array
Search a 2D Matrix II (official problem, opens in a new tab)
Reveal learning notes Additional foundation
- What this teaches
- Distinguish row-and-column monotonicity from the stronger global ordering required by flattening.
- Target approach
- Staircase elimination from a corner; prove an entire row or column can be discarded.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Search a 2D Matrix
Find Peak Element (official problem, opens in a new tab)
Reveal learning notes Additional foundation
- What this teaches
- Use a guaranteed peak in the retained half even though the local slope predicate is not globally monotone.
- Target approach
- Slope-guided interval halving with a peak-existence invariant; do not claim ordinary first-true monotonicity.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
- Build on
- Binary Search
Magnetic Force Between Two Balls (official problem, opens in a new tab)
Reveal learning notes #16
- What this teaches
- Reverse the search direction for maximizing a feasible minimum separation.
- Target approach
- Sort positions; binary search the last feasible distance using earliest-possible greedy placement.
- Pattern coverage
- #16 Binary search on the answer
Insert Interval (official problem, opens in a new tab)
Reveal learning notes #17
- What this teaches
- Exploit already sorted disjoint ranges to avoid sorting during insertion.
- Target approach
- Emit intervals before the new range, merge overlaps, then append the untouched suffix.
- Pattern coverage
- #17 Sort and merge intervals
- Build on
- Merge Intervals
Interval List Intersections (official problem, opens in a new tab)
Reveal learning notes #17
- What this teaches
- Combine two ordered disjoint interval streams and discard the one that ends first.
- Target approach
- Compute max(start) and min(end) intersections; advance the smaller end.
- Pattern coverage
- #17 Sort and merge intervals
- Build on
- Merge Intervals
Linked List Cycle II (official problem, opens in a new tab)
Reveal learning notes #23
- What this teaches
- Derive the cycle entry from the first meeting point instead of stopping at detection.
- Target approach
- After a Floyd meeting, reset one pointer to the head and advance both one step at a time.
- Pattern coverage
- #23 Fast-slow pointers
- Build on
- Linked List Cycle
Find the Duplicate Number (official problem, opens in a new tab)
Reveal learning notes #23
- What this teaches
- Recognize a functional graph hidden inside an array with constrained values.
- Target approach
- Treat index-to-value as a successor function and locate its cycle entry without modifying the array.
- Pattern coverage
- #23 Fast-slow pointers
- Build on
- Linked List Cycle II
Reverse Linked List II (official problem, opens in a new tab)
Reveal learning notes #24
- What this teaches
- Reconnect a reversed subrange to both outside neighbors, including a range beginning at the head.
- Target approach
- Dummy predecessor plus bounded in-place reversal; preserve the original subrange head as its new tail.
- Pattern coverage
- #24 Linked-list reversal
- Build on
- Reverse Linked List
Palindrome Linked List (official problem, opens in a new tab)
Reveal learning notes #23, #24
- What this teaches
- Compare symmetric list positions using constant extra space and restore any temporary mutation.
- Target approach
- Find the midpoint, reverse one half, compare, then restore the reversed links.
- Pattern coverage
- #23 Fast-slow pointers; #24 Linked-list reversal
- Build on
- Reverse Linked List; Linked List Cycle
Reveal learning notes Additional foundation
- What this teaches
- Equalize total traversal distance without comparing node values or altering either list.
- Target approach
- Redirect each pointer to the other head after its own tail; stop at shared identity or simultaneous null.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Copy List with Random Pointer (official problem, opens in a new tab)
Reveal learning notes #01
- What this teaches
- Clone a structure with cross-links while preserving aliasing relationships.
- Target approach
- Map original nodes to clones in two passes; explain the interleaving alternative and its mutation requirement.
- Pattern coverage
- #01 Hash lookup and frequency
- Build on
- Two Sum
Insert Delete GetRandom O(1) - Duplicates allowed (official problem, opens in a new tab)
Reveal learning notes #71
- What this teaches
- Duplicate values turn the position map into a set of positions, making swap bookkeeping more delicate.
- Target approach
- Combine an array with value-to-index-set mappings and repair both moved and removed memberships during swap-and-pop.
- Pattern coverage
- #71 Composite structures for operation guarantees
- Build on
- Insert Delete GetRandom O(1)
LFU Cache (official problem, opens in a new tab)
Reveal learning notes #71
- What this teaches
- Least frequency plus recency tie-breaking requires maintaining both frequency buckets and order within each bucket.
- Target approach
- Use key-to-node lookup, a doubly linked recency list per frequency, and a tracked minimum frequency for expected O(1) operations.
- Pattern coverage
- #71 Composite structures for operation guarantees
- Build on
- LRU Cache
Random Pick with Weight (official problem, opens in a new tab)
Reveal learning notes #07, #15
- What this teaches
- Translate probabilities into disjoint cumulative-weight intervals and avoid boundary bias.
- Target approach
- Positive prefix weights plus a uniform integer draw and lower_bound; justify each index's probability.
- Pattern coverage
- #07 Prefix aggregates; #15 Binary search for a boundary
- Build on
- Binary Search; Range Sum Query - Immutable
Flatten Nested List Iterator (official problem, opens in a new tab)
Reveal learning notes #14, #71
- What this teaches
- Preserve traversal state between API calls and distinguish eager preprocessing from lazy iteration.
- Target approach
- Explicit iterator stack with hasNext advancing to the next integer; explain total versus per-call work.
- Pattern coverage
- #14 Stack for nested structure; #71 Composite structures for operation guarantees
- Build on
- Binary Tree Inorder Traversal
K Closest Points to Origin (official problem, opens in a new tab)
Reveal learning notes #19, #22
- What this teaches
- Transfer selection to records with a derived priority and no need for a sorted answer.
- Target approach
- Use squared distance and a size-k max-heap; then implement randomized quickselect over the same key.
- Pattern coverage
- #19 Heap for top k; #22 Quickselect
- Build on
- Kth Largest Element in an Array
Find K Pairs with Smallest Sums (official problem, opens in a new tab)
Reveal learning notes #20
- What this teaches
- Model an implicit pair-sum matrix as sorted streams and expose only their frontiers.
- Target approach
- Heap-merge rows of nums1[i]+nums2[j], seeding at most min(k,len(nums1)) rows.
- Pattern coverage
- #20 Heap for k-way merge
- Build on
- Merge k Sorted Lists
Gas Station (official problem, opens in a new tab)
Reveal learning notes #50
- What this teaches
- A failed running-surplus segment rules out every starting point inside that segment.
- Target approach
- Use total fuel feasibility plus a candidate start reset after negative running surplus; prove the eliminated-start property.
- Pattern coverage
- #50 Greedy choice with an exchange proof
Candy (official problem, opens in a new tab)
Reveal learning notes #50
- What this teaches
- Neighbor constraints run in two directions, so one directional local pass is insufficient.
- Target approach
- Compute minimum candies satisfying left neighbors, then scan from the right and take the larger requirement at each position.
- Pattern coverage
- #50 Greedy choice with an exchange proof
Course Schedule III (official problem, opens in a new tab)
Reveal learning notes #50, #51
- What this teaches
- When a deadline is exceeded, replacing the longest retained course can improve feasibility without reducing the retained count.
- Target approach
- Sort by deadline, accumulate durations in a max-heap, and remove the longest course whenever the running time exceeds the current deadline.
- Pattern coverage
- #50 Greedy choice with an exchange proof; #51 Greedy scheduling with a heap
Meeting Rooms III (official problem, opens in a new tab)
Reveal learning notes #51
- What this teaches
- Deterministic resource IDs and delayed jobs require two priorities and careful tie handling.
- Target approach
- Sort meetings, release all rooms available by the next start into a min-ID heap, and otherwise delay into the earliest (end time, room ID) from a busy heap.
- Pattern coverage
- #51 Greedy scheduling with a heap
- Build on
- Room Allocation
Symmetric Tree (official problem, opens in a new tab)
Reveal learning notes #25
- What this teaches
- A mirrored relationship changes which child pairs must be compared.
- Target approach
- Paired traversal comparing left with right and right with left.
- Pattern coverage
- #25 DFS / flood fill
- Build on
- Same Tree
House Robber III (official problem, opens in a new tab)
Reveal learning notes #36, #48
- What this teaches
- Return take and skip states because a parent choice constrains its children.
- Target approach
- Postorder tree DP returning best sums with and without each node.
- Pattern coverage
- #36 Tree postorder DP; #48 Finite-state DP: stock / cooldown
- Build on
- House Robber; Maximum Depth of Binary Tree
Sum of Distances in Tree (official problem, opens in a new tab)
Reveal learning notes #36, #66
- What this teaches
- Move the root across an edge by subtracting one subtree contribution and adding the complement. Moving a root across an edge makes one subtree closer and all other nodes farther.
- Target approach
- Two-pass rerooting DP with subtree sizes and distance sums. Additional focus: Compute subtree sizes and one distance sum, then propagate answer[child] = answer[parent] + n - 2 * subtreeSize[child].
- Pattern coverage
- #36 Tree postorder DP; #66 Rerooting tree DP
- Build on
- Diameter of Binary Tree
Binary Search Tree Iterator (official problem, opens in a new tab)
Reveal learning notes #37
- What this teaches
- Preserve a traversal frontier so the next value can be produced lazily.
- Target approach
- Maintain a stack of the next left spine and analyze amortized next() cost.
- Pattern coverage
- #37 BST ordering / inorder traversal
- Build on
- Kth Smallest Element in a BST
Delete Node in a BST (official problem, opens in a new tab)
Reveal learning notes #37
- What this teaches
- Deleting a two-child node requires a replacement whose removal preserves ordering.
- Target approach
- BST search followed by leaf, one-child, or successor/predecessor replacement cases.
- Pattern coverage
- #37 BST ordering / inorder traversal
- Build on
- Validate Binary Search Tree
Lowest Common Ancestor of a Binary Search Tree (official problem, opens in a new tab)
Reveal learning notes #37, #38
- What this teaches
- Ordering lets both search paths be followed until their directions diverge.
- Target approach
- Iterative BST descent using both target values.
- Pattern coverage
- #37 BST ordering / inorder traversal; #38 LCA / binary lifting
Path Sum III (official problem, opens in a new tab)
Reveal learning notes #08, #25
- What this teaches
- Keep prefix counts local to the current root-to-node path; undo them when returning from a branch.
- Target approach
- DFS with a prefix-frequency map and rollback; explain why prefixes from sibling branches must not mix.
- Pattern coverage
- #08 Prefix sum plus hash map; #25 DFS / flood fill
- Build on
- Subarray Sum Equals K; Path Sum
01 Matrix (official problem, opens in a new tab)
Reveal learning notes #26
- What this teaches
- Transform many nearest-target searches into one nearest-source distance computation.
- Target approach
- Multi-source BFS from all zero cells.
- Pattern coverage
- #26 BFS / multi-source BFS
- Build on
- Rotting Oranges
Shortest Path in a Grid with Obstacles Elimination (official problem, opens in a new tab)
Reveal learning notes #26, #67
- What this teaches
- A location reached with different remaining resources represents different future options. The same cell reached with a different obstacle-removal budget may represent a different useful future.
- Target approach
- BFS over (row, column, remaining eliminations); justify any dominance pruning. Additional focus: Run BFS on (row, column, eliminationsRemaining); if compressing visited state, justify dominance using nondecreasing BFS distance.
- Pattern coverage
- #26 BFS / multi-source BFS; #67 Expanded-state graph search
- Build on
- Rotting Oranges
Path With Minimum Effort (official problem, opens in a new tab)
Reveal learning notes #28
- What this teaches
- The cost of a route can aggregate with maximum instead of sum.
- Target approach
- Dijkstra using candidate = max(current effort, edge effort); justify monotonicity.
- Pattern coverage
- #28 Dijkstra's shortest paths
- Build on
- Network Delay Time
Path with Maximum Probability (official problem, opens in a new tab)
Reveal learning notes #28
- What this teaches
- The same finalization argument works for decreasing probability products with a max-heap.
- Target approach
- Maximum-probability Dijkstra with multiplicative relaxation.
- Pattern coverage
- #28 Dijkstra's shortest paths
- Build on
- Network Delay Time
Evaluate Division (official problem, opens in a new tab)
Reveal learning notes #25, #32
- What this teaches
- Ratios are edge relations and a weighted DSU must preserve each node-to-parent potential.
- Target approach
- First solve by graph DFS; then implement weighted DSU and derive its union ratio.
- Pattern coverage
- #25 DFS / flood fill; #32 Union–find / disjoint-set union
- Build on
- Accounts Merge
Find Eventual Safe States (official problem, opens in a new tab)
Reveal learning notes #31, #35, #68
- What this teaches
- A vertex is unsafe if any reachable route can remain in a directed cycle. Nodes safe from all cycles can be removed backward starting at terminal nodes.
- Target approach
- Reverse-graph outdegree elimination; also explain DFS active and resolved states. Additional focus: Reverse directed edges, maintain original outdegrees, and repeatedly remove zero-outdegree nodes; report all nodes removed.
- Pattern coverage
- #31 Topological ordering / DAG DP; #35 DFS cycle states / strongly connected components; #68 Reverse reasoning / reverse graph
- Build on
- Course Schedule
Subsets II (official problem, opens in a new tab)
Reveal learning notes #49
- What this teaches
- Equal values must be skipped at the same recursion depth without suppressing legitimate repeated values at deeper levels.
- Target approach
- Sort and use depth-local duplicate skipping in increasing-index subset DFS.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Subsets
Permutations II (official problem, opens in a new tab)
Reveal learning notes #49
- What this teaches
- Duplicate permutations require controlling which identical unused copy may be chosen next.
- Target approach
- Use sorted values plus a used array with a same-value predecessor rule, or recurse on value frequencies.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Permutations; Subsets II
Combination Sum II (official problem, opens in a new tab)
Reveal learning notes #49
- What this teaches
- Combining one-use candidates with duplicate values requires both advancing the index and suppressing equivalent sibling branches.
- Target approach
- Sort, recurse from index + 1 after choosing a candidate, skip equal values at one depth, and prune positive candidates above the remaining target.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Combination Sum; Subsets II
N-Queens (official problem, opens in a new tab)
Reveal learning notes #49
- What this teaches
- A valid placement can be tested from occupied columns and diagonals rather than rescanning the board.
- Target approach
- Place one queen per row and maintain column, row-column, and row+column occupancy sets or masks.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Generate Parentheses; Permutations
Palindrome Partitioning (official problem, opens in a new tab)
Reveal learning notes #49, #56
- What this teaches
- A partition search becomes cheaper when validity of each candidate substring is precomputed.
- Target approach
- Build a palindrome interval DP table, then enumerate cut positions with DFS using that table.
- Pattern coverage
- #49 Backtracking and pruning; #56 Palindrome centers / palindrome DP
- Build on
- Subsets; Palindromic Substrings
Word Break II (official problem, opens in a new tab)
Reveal learning notes #49
- What this teaches
- Enumerating all valid segmentations requires retaining every valid continuation rather than only a boolean reachability result.
- Target approach
- Build or memoize valid suffix segmentations by start index, optionally prune unreachable suffixes, and account for total output length.
- Pattern coverage
- #49 Backtracking and pruning
- Build on
- Combination Sum; Word Break
Closest Subsequence Sum (official problem, opens in a new tab)
Reveal learning notes #52
- What this teaches
- About forty signed choices favor half-subset enumeration; positive-only pruning is unavailable.
- Target approach
- Enumerate both halves, sort one half, and binary search the nearest complement for every sum in the other half.
- Pattern coverage
- #52 Meet in the middle
Word Search II (official problem, opens in a new tab)
Reveal learning notes #49, #53
- What this teaches
- Searching a board for many words can share dictionary prefixes instead of repeating a full search for every word.
- Target approach
- Build a trie and DFS from each board cell with visited-cell restoration; suppress duplicate emitted words and optionally prune exhausted trie branches.
- Pattern coverage
- #49 Backtracking and pruning; #53 Trie / prefix tree
Search Suggestions System (official problem, opens in a new tab)
Reveal learning notes #53
- What this teaches
- A small requested output per prefix can be cached in trie nodes during construction.
- Target approach
- Use a trie with the lexicographically smallest three suggestions per node; also explain the sorted-array lower-bound alternative.
- Pattern coverage
- #53 Trie / prefix tree
- Build on
- Implement Trie (Prefix Tree)
Reveal learning notes #53, #57
- What this teaches
- The largest XOR is chosen from the most significant bit downward, where a higher differing bit dominates all lower bits.
- Target approach
- Build a binary trie and greedily query opposite bits from most to least significant; use the problem input width.
- Pattern coverage
- #53 Trie / prefix tree; #57 XOR, bit masks, and bit counts
Shortest Path to Get All Keys (official problem, opens in a new tab)
Reveal learning notes #26, #46, #57, #67
- What this teaches
- Include the collected-key mask in visited state because possession changes legal moves. Returning to a cell with a new key set can unlock transitions that were previously impossible.
- Target approach
- BFS over (row, column, key mask), updating the mask before the visited check. Additional focus: Run BFS on (row, column, collectedKeysMask) and mark the entire state visited.
- Pattern coverage
- #26 BFS / multi-source BFS; #46 Bitmask DP; #57 XOR, bit masks, and bit counts; #67 Expanded-state graph search
House Robber II (official problem, opens in a new tab)
Reveal learning notes #39, #48
- What this teaches
- A cyclic dependency can be removed by conditioning on mutually exclusive endpoints.
- Target approach
- Reduce to two linear robber ranges with small-input handling.
- Pattern coverage
- #39 Memoization / one-dimensional DP; #48 Finite-state DP: stock / cooldown
- Build on
- House Robber
Unique Paths II (official problem, opens in a new tab)
Reveal learning notes #40
- What this teaches
- An obstacle must reset a compressed state so paths cannot leak through blocked cells.
- Target approach
- One-row path-count DP with blocked-cell and boundary initialization.
- Pattern coverage
- #40 Grid DP
- Build on
- Unique Paths
Dungeon Game (official problem, opens in a new tab)
Reveal learning notes #40
- What this teaches
- Work backward with required entering health because cumulative path sum loses the minimum-prefix constraint.
- Target approach
- Reverse grid DP with minimum required health clamped to one.
- Pattern coverage
- #40 Grid DP
- Build on
- Minimum Path Sum
Cherry Pickup II (official problem, opens in a new tab)
Reveal learning notes #40
- What this teaches
- Synchronized agents share one time or row index but require separate positions, and overlapping rewards must be counted once.
- Target approach
- DP over (row, first column, second column), considering both robots’ moves together and rolling the row dimension.
- Pattern coverage
- #40 Grid DP
- Build on
- Minimum Path Sum
Ones and Zeroes (official problem, opens in a new tab)
Reveal learning notes #41
- What this teaches
- Two independent resource budgets require two capacity dimensions and descending updates in both.
- Target approach
- Two-capacity 0/1 knapsack maximizing the number of chosen strings.
- Pattern coverage
- #41 0/1 knapsack / subset sum
- Build on
- Partition Equal Subset Sum
Combination Sum IV (official problem, opens in a new tab)
Reveal learning notes #42
- What this teaches
- Changing the loop order counts ordered constructions instead of unordered combinations.
- Target approach
- Amount-first counting DP with each number treated as the final choice.
- Pattern coverage
- #42 Unbounded knapsack / coin change
- Build on
- Coin Change II
Distinct Subsequences (official problem, opens in a new tab)
Reveal learning notes #43
- What this teaches
- Counting embeddings requires adding alternatives even when a match is possible.
- Target approach
- Two-sequence count DP; if compressed, update the target index backward.
- Pattern coverage
- #43 Two-sequence DP: LCS / edit distance
- Build on
- Longest Common Subsequence
Interleaving String (official problem, opens in a new tab)
Reveal learning notes #43
- What this teaches
- Two consumed-prefix lengths determine the third position, so a third state dimension is redundant.
- Target approach
- Boolean two-sequence DP with target index i + j and a length precheck.
- Pattern coverage
- #43 Two-sequence DP: LCS / edit distance
- Build on
- Longest Common Subsequence
Regular Expression Matching (official problem, opens in a new tab)
Reveal learning notes #43
- What this teaches
- A repetition operator branches between skipping its token and consuming another matching character.
- Target approach
- Memoized text-pattern indices or equivalent DP supporting only the specified dot and star rules.
- Pattern coverage
- #43 Two-sequence DP: LCS / edit distance
- Build on
- Edit Distance
Russian Doll Envelopes (official problem, opens in a new tab)
Reveal learning notes #44
- What this teaches
- Sorting one dimension needs a reversed tie order to prevent illegal equality in the remaining LIS.
- Target approach
- Sort widths ascending and tied heights descending, then strict height LIS.
- Pattern coverage
- #44 Longest increasing subsequence: tails
- Build on
- Longest Increasing Subsequence
Reveal learning notes #39, #44
- What this teaches
- The shortest tail alone cannot preserve how many optimal subsequences exist.
- Target approach
- Quadratic DP storing both best ending length and its count.
- Pattern coverage
- #39 Memoization / one-dimensional DP; #44 Longest increasing subsequence: tails
- Build on
- Longest Increasing Subsequence
Burst Balloons (official problem, opens in a new tab)
Reveal learning notes #45
- What this teaches
- Choosing the last removal fixes the two outside neighbors of an interval.
- Target approach
- Interval DP with padded boundary values and every possible final balloon.
- Pattern coverage
- #45 Interval DP
- Build on
- Longest Palindromic Subsequence
Minimum Cost to Cut a Stick (official problem, opens in a new tab)
Reveal learning notes #45
- What this teaches
- Choosing a cut splits an interval into independent pieces with a shared boundary-dependent cost.
- Target approach
- Sorted-cut interval DP with stick endpoints inserted as sentinels.
- Pattern coverage
- #45 Interval DP
- Build on
- Burst Balloons
Best Time to Buy and Sell Stock with Transaction Fee (official problem, opens in a new tab)
Reveal learning notes #48
- What this teaches
- Attach a transaction fee to exactly one action while preserving state transition meaning.
- Target approach
- Holding and cash DP with a fee charged once per completed trade.
- Pattern coverage
- #48 Finite-state DP: stock / cooldown
Reveal learning notes #48
- What this teaches
- A bounded number of transactions adds a budget dimension whose updates must respect day order.
- Target approach
- O(nk) holding/cash DP with transaction counts and the unlimited-transactions shortcut.
- Pattern coverage
- #48 Finite-state DP: stock / cooldown
Longest Happy Prefix (official problem, opens in a new tab)
Reveal learning notes #54
- What this teaches
- A proper prefix that is also a suffix is exactly the terminal prefix-function value.
- Target approach
- Build the KMP prefix-function array and return the longest proper border from its final entry.
- Pattern coverage
- #54 KMP / Z-function matching
Shortest Palindrome (official problem, opens in a new tab)
Reveal learning notes #54
- What this teaches
- Prepending the fewest characters reduces to finding the longest palindromic prefix.
- Target approach
- Use the prefix function on s + an out-of-alphabet separator + reverse(s), then prepend the reverse of the unmatched suffix.
- Pattern coverage
- #54 KMP / Z-function matching
- Build on
- Longest Happy Prefix
Single Number III (official problem, opens in a new tab)
Reveal learning notes #57
- What this teaches
- Two unique values can be separated by one bit on which they differ.
- Target approach
- XOR all values, isolate one set bit, partition values by that bit, and XOR within each partition.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
- Build on
- Single Number; Number of 1 Bits
Single Number II (official problem, opens in a new tab)
Reveal learning notes #57
- What this teaches
- Triplicate cancellation requires counts modulo three at each bit position instead of ordinary XOR.
- Target approach
- Count each fixed-width bit modulo three and reconstruct the signed answer correctly.
- Pattern coverage
- #57 XOR, bit masks, and bit counts
- Build on
- Single Number
Exponentiation (official problem, opens in a new tab)
Reveal learning notes #58
- What this teaches
- A huge exponent is manageable when repeated squaring composes identical multiplication steps.
- Target approach
- Implement modular binary exponentiation, handle exponent zero, and use multiplication wide enough for the given modulus.
- Pattern coverage
- #58 GCD and modular arithmetic
Count Primes (official problem, opens in a new tab)
Reveal learning notes #59
- What this teaches
- Testing every candidate by trial division wastes work when all candidates share one upper bound.
- Target approach
- Implement the sieve of Eratosthenes, mark from p*p, and treat the bound as exclusive.
- Pattern coverage
- #59 Sieve and divisor preprocessing
Reveal learning notes #60, #63
- What this teaches
- Scanning from the right turns later-smaller counting into prefix frequency queries over compressed values.
- Target approach
- Coordinate-compress unique values and use a Fenwick frequency tree; query ranks strictly below the current rank before inserting it.
- Pattern coverage
- #60 Fenwick tree / binary indexed tree; #63 Coordinate compression
- Build on
- Range Sum Query - Mutable
Checking Existence of Edge Length Limited Paths (official problem, opens in a new tab)
Reveal learning notes #64
- What this teaches
- Sorting queries by an edge-weight limit turns each answer into connectivity among currently activated edges.
- Target approach
- Sort edges and indexed queries by threshold, add only edges with weight strictly below each threshold to DSU, and restore original query order.
- Pattern coverage
- #64 Offline query ordering
- Build on
- Redundant Connection
Reveal learning notes #70
- What this teaches
- A range-sum condition becomes a bounded difference between prefix sums while their original index order remains essential.
- Target approach
- Form prefix sums and use merge-sort counting with two monotone pointers to count right-half values in each left prefix sum plus [lower, upper].
- Pattern coverage
- #70 Merge-sort counting / divide and conquer
- Build on
- Reverse Pairs
Reveal learning notes #07, #13
- What this teaches
- Recover shortest qualifying subarrays with negatives by dominating prefix candidates instead of using an ordinary sum window.
- Target approach
- Increasing deque of prefix sums; pop feasible starts from front and dominated starts from back.
- Pattern coverage
- #07 Prefix aggregates; #13 Monotonic deque
Reveal learning notes #14
- What this teaches
- Handle signs, nested parentheses, and unary minus without assuming every minus has two operands.
- Target approach
- Sign/context stack or explicit nested parser; evaluate according to the problem's actual operator set.
- Pattern coverage
- #14 Stack for nested structure
Reveal learning notes #15
- What this teaches
- Search partition positions rather than values while preserving the number of elements in the lower half.
- Target approach
- Binary search a partition of the shorter array; enforce both cross-boundary ordering inequalities.
- Pattern coverage
- #15 Binary search for a boundary
Reveal learning notes #05, #16
- What this teaches
- Find a rank in an implicit quadratic multiset by counting how many values fall below a candidate.
- Target approach
- Sort; binary search distance; count pairs within that distance using two moving boundaries.
- Pattern coverage
- #05 Variable-size sliding window; #16 Binary search on the answer
Reveal learning notes #18
- What this teaches
- Maintain a changing maximum over active intervals while grouping simultaneous coordinates.
- Target approach
- Sweep building endpoints with an active-height multiset or heap with lazy expiry; emit only changes in visible height.
- Pattern coverage
- #18 Sweep line and events
Reveal learning notes #24
- What this teaches
- Check a complete group exists before committing a local structural transformation.
- Target approach
- Locate the kth node, reverse exactly k links, reconnect groups, and leave a short suffix unchanged.
- Pattern coverage
- #24 Linked-list reversal
- Build on
- Reverse Linked List II
Reveal learning notes #71
- What this teaches
- Increment/decrement by one enables adjacent frequency buckets and constant-time minimum/maximum access.
- Target approach
- Use a doubly linked ordered list of count buckets with key sets and a key-to-bucket map; create and delete neighboring buckets as necessary.
- Pattern coverage
- #71 Composite structures for operation guarantees
- Build on
- LFU Cache
Reveal learning notes #20
- What this teaches
- Maintain coverage of every source while minimizing the span between the smallest and largest exposed values.
- Target approach
- Heap of one current value per list plus a running maximum; advance the minimum source until one list ends.
- Pattern coverage
- #20 Heap for k-way merge
- Build on
- Merge k Sorted Lists
Reveal learning notes #21
- What this teaches
- Support window expirations without confusing physical heap size with the number of live elements.
- Target approach
- Dual heaps with delayed deletion, logical sizes, and root pruning; periodically rebuild to bound stale storage, or explicitly document unbounded lazy-heap growth.
- Pattern coverage
- #21 Two heaps for a median
Reveal learning notes #38
- What this teaches
- Repeated ancestry queries justify precomputing powers-of-two jumps.
- Target approach
- Binary lifting with safe missing-ancestor handling.
- Pattern coverage
- #38 LCA / binary lifting
Distance Queries (official problem, opens in a new tab)
Reveal learning notes #38
- What this teaches
- Two root distances and a lowest common ancestor determine an arbitrary tree path length.
- Target approach
- Binary lifting LCA plus depth[a] + depth[b] − 2 × depth[lca].
- Pattern coverage
- #38 LCA / binary lifting
- Build on
- Kth Ancestor of a Tree Node
Reveal learning notes #55
- What this teaches
- Repeated-substring length is monotone, but a hash match is only a candidate equality.
- Target approach
- Binary search the length and use rolling hashes to group candidates; verify actual substring equality within hash buckets, including collisions, and discuss verification worst cases.
- Pattern coverage
- #55 Rolling hash for substring queries
Subtree Queries (official problem, opens in a new tab)
Reveal learning notes #60, #65
- What this teaches
- A subtree becomes a contiguous interval in entry-only DFS order.
- Target approach
- Compute tin/tout intervals, place node values in Euler-entry order, and use Fenwick point deltas plus subtree interval sums.
- Pattern coverage
- #60 Fenwick tree / binary indexed tree; #65 Euler tour tree flattening
- Build on
- Range Sum Query - Mutable
Tree Distances I (official problem, opens in a new tab)
Reveal learning notes #66
- What this teaches
- Farthest-distance answers need a way to exclude the child branch when propagating an outside contribution.
- Target approach
- Use two-pass rerooting DP with downward best distances and the best two child contributions; do not use diameter endpoints for this exercise.
- Pattern coverage
- #66 Rerooting tree DP
- Build on
- Sum of Distances in Tree
Minimum Cost to Make at Least One Valid Path in a Grid (official problem, opens in a new tab)
Reveal learning notes #27
- What this teaches
- A free preferred move and a paid changed move produce exactly zero-one edge weights.
- Target approach
- 0–1 BFS with distance relaxation and a deque; Dijkstra alone does not complete this lesson.
- Pattern coverage
- #27 0–1 BFS
- Build on
- Rotting Oranges
Cycle Finding (official problem, opens in a new tab)
Reveal learning notes #29
- What this teaches
- Detect a negative cycle anywhere and recover a concrete cycle from predecessor links.
- Target approach
- Bellman–Ford with a virtual super-source or all-zero initial distances, followed by predecessor walking.
- Pattern coverage
- #29 Bellman–Ford
- Build on
- Cheapest Flights Within K Stops
Find the City With the Smallest Number of Neighbors at a Threshold Distance (official problem, opens in a new tab)
Reveal learning notes #30
- What this teaches
- A small graph and all-pairs questions justify a distance matrix and cubic preprocessing.
- Target approach
- Floyd–Warshall with the intermediate vertex outermost, then apply the tie rule.
- Pattern coverage
- #30 Floyd–Warshall
- Build on
- Network Delay Time
Reveal learning notes #31
- What this teaches
- Topological propagation may carry a vector of best counts instead of a scalar distance.
- Target approach
- Kahn traversal with one color-count vector per vertex and explicit cycle rejection.
- Pattern coverage
- #31 Topological ordering / DAG DP
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree (official problem, opens in a new tab)
Reveal learning notes #32, #33
- What this teaches
- Determine whether an edge is forced, optional, or excluded across optimal spanning trees.
- Target approach
- Repeated Kruskal runs excluding and forcing each edge, preserving original edge identities.
- Pattern coverage
- #32 Union–find / disjoint-set union; #33 Minimum spanning tree
- Build on
- Min Cost to Connect All Points
Planets and Kingdoms (official problem, opens in a new tab)
Reveal learning notes #35
- What this teaches
- Mutual reachability requires strongly connected components rather than ordinary DFS components.
- Target approach
- Kosaraju or Tarjan SCC decomposition, and explain why component contraction is acyclic.
- Pattern coverage
- #35 DFS cycle states / strongly connected components
- Build on
- Course Schedule
Reveal learning notes #68
- What this teaches
- Deletion is difficult for ordinary DSU, but reversing all hits converts the process into additions.
- Target approach
- Apply hits, build DSU on remaining bricks with a virtual roof, then restore valid hits backward and measure the roof-component growth minus the restored brick. Report max(0, newRoofSize - oldRoofSize - 1) after a real restoration; originally empty hits report zero.
- Pattern coverage
- #68 Reverse reasoning / reverse graph
- Build on
- Redundant Connection
Reveal learning notes Additional foundation
- What this teaches
- A tree edge is a bridge exactly when its child subtree cannot reach the parent or an ancestor through another edge.
- Target approach
- Implement DFS discovery times and low-link values; identify bridges using low[child] > discovery[parent] and track parent edges carefully.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Reveal learning notes Additional foundation
- What this teaches
- Using every ticket exactly once is an edge-visitation problem; ordinary vertex DFS does not model the objective.
- Target approach
- Use Hierholzer traversal from JFK with lexicographically ordered outgoing edges and reverse the postorder route; account for duplicate tickets.
- Pattern coverage
- A supporting interview technique outside the 72-pattern index.
Flight Discount (official problem, opens in a new tab)
Reveal learning notes #28, #67
- What this teaches
- Combine unequal edge weights with a one-use resource that changes future costs.
- Target approach
- Require Dijkstra on (city,discountUsed), with a transition costing floor(edgeWeight/2) when consuming the discount. Compare with two shortest-path passes as a second solution.
- Pattern coverage
- #28 Dijkstra's shortest paths; #67 Expanded-state graph search
- Build on
- Network Delay Time
Sudoku Solver (official problem, opens in a new tab)
Reveal learning notes #49, #57
- What this teaches
- Constraint propagation and choosing the most restricted variable can shrink an otherwise enormous assignment search.
- Target approach
- Maintain row/column/box masks, choose an empty cell with fewest legal digits, and undo every placement on backtracking.
- Pattern coverage
- #49 Backtracking and pruning; #57 XOR, bit masks, and bit counts
- Build on
- N-Queens
Partition Array Into Two Arrays to Minimize Sum Difference (official problem, opens in a new tab)
Reveal learning notes #52
- What this teaches
- An exact chosen-element count requires grouping half sums by cardinality before joining them.
- Target approach
- Enumerate each half into buckets by selected count, then combine complementary counts with sorting and nearest-complement search.
- Pattern coverage
- #52 Meet in the middle
- Build on
- Closest Subsequence Sum
Meet in the Middle (official problem, opens in a new tab)
Reveal learning notes #52
- What this teaches
- Counting subsets needs multiplicities of equal half sums, which nearest-sum optimization may ignore.
- Target approach
- Enumerate half sums and count all complementary sum pairs using frequency maps or sorted runs; keep duplicate sums.
- Pattern coverage
- #52 Meet in the middle
- Build on
- Closest Subsequence Sum
Can I Win (official problem, opens in a new tab)
Reveal learning notes #46
- What this teaches
- Histories with the same used-number set have the same remaining total and winning options.
- Target approach
- Memoized winning-state bitmask DP with immediate-win and total-sum feasibility checks.
- Pattern coverage
- #46 Bitmask DP
- Build on
- Climbing Stairs
Reveal learning notes #46
- What this teaches
- A used-partner mask determines the next assignment index through its population count.
- Target approach
- Assignment DP over subsets, adding one unused partner per transition.
- Pattern coverage
- #46 Bitmask DP
- Build on
- Partition Equal Subset Sum
Reveal learning notes #26, #46, #57, #67
- What this teaches
- A visit-all route needs both a collected subset and a current endpoint, and may revisit nodes. The set of visited vertices belongs in the state when completion requires visiting every node.
- Target approach
- Multi-source BFS over (node, visited mask); contrast with acyclic Hamiltonian subset DP. Additional focus: Run multi-source BFS from every (startNode, singletonMask) and stop at the full visited mask.
- Pattern coverage
- #26 BFS / multi-source BFS; #46 Bitmask DP; #57 XOR, bit masks, and bit counts; #67 Expanded-state graph search
- Build on
- Shortest Path to Get All Keys
Hamiltonian Flights (official problem, opens in a new tab)
Reveal learning notes #46
- What this teaches
- A subset alone cannot identify which incoming edges can extend a partial route.
- Target approach
- Counting DP over (visited mask, last vertex), with start/end restrictions and multiplicities.
- Pattern coverage
- #46 Bitmask DP
- Build on
- Minimum XOR Sum of Two Arrays
Reveal learning notes #47
- What this teaches
- Digit position, tightness, leading-zero status, and used digits summarize exponentially many numbers.
- Target approach
- Digit DP with a used-digit mask, a started flag, and a tight bound.
- Pattern coverage
- #47 Digit DP
- Build on
- Minimum XOR Sum of Two Arrays
Fibonacci Numbers (official problem, opens in a new tab)
Reveal learning notes #58, #69
- What this teaches
- A constant-size linear recurrence can jump across an enormous index by composing its transition matrix.
- Target approach
- Implement 2-by-2 matrix exponentiation modulo the specified modulus, derive the initial vector, and test indices zero and one.
- Pattern coverage
- #58 GCD and modular arithmetic; #69 Matrix / transition exponentiation
- Build on
- Exponentiation
Graph Paths I (official problem, opens in a new tab)
Reveal learning notes #58, #69
- What this teaches
- Exactly-k-step walk counts are entries of an adjacency matrix power, including contributions from parallel edges.
- Target approach
- Use adjacency-matrix exponentiation over modular sum/product arithmetic and read the required source-to-target entry.
- Pattern coverage
- #58 GCD and modular arithmetic; #69 Matrix / transition exponentiation
- Build on
- Fibonacci Numbers
String Matching (official problem, opens in a new tab)
Reveal learning notes #54
- What this teaches
- Counting all occurrences must preserve overlaps after a complete match.
- Target approach
- Implement Z-function matching on pattern + a separator outside the alphabet + text, and count all positions with Z at least the pattern length.
- Pattern coverage
- #54 KMP / Z-function matching
Binomial Coefficients (official problem, opens in a new tab)
Reveal learning notes #58
- What this teaches
- Many binomial queries under a prime modulus benefit from factorial and inverse-factorial preprocessing.
- Target approach
- Precompute factorials and modular inverse factorials using Fermat exponentiation; explain why the prime modulus and argument bounds permit these inverses.
- Pattern coverage
- #58 GCD and modular arithmetic
- Build on
- Exponentiation
Counting Divisors (official problem, opens in a new tab)
Reveal learning notes #59
- What this teaches
- Repeated bounded divisor queries can share factorization work.
- Target approach
- Precompute smallest prime factors up to the maximum input, factor each query, and multiply one plus each prime exponent.
- Pattern coverage
- #59 Sieve and divisor preprocessing
- Build on
- Count Primes
List Removals (official problem, opens in a new tab)
Reveal learning notes #60
- What this teaches
- Removing the kth live position is an order-statistic query on nonnegative frequencies.
- Target approach
- Initialize a Fenwick tree of ones, locate the kth live element by Fenwick binary lifting, then subtract its frequency.
- Pattern coverage
- #60 Fenwick tree / binary indexed tree
- Build on
- Range Sum Query - Mutable
Dynamic Range Minimum Queries (official problem, opens in a new tab)
Reveal learning notes #61
- What this teaches
- Arbitrary point replacement and range minimum need an associative aggregate rather than prefix subtraction.
- Target approach
- Build a segment tree storing minimum with an infinity identity and support point assignments and interval queries.
- Pattern coverage
- #61 Segment tree / lazy propagation
- Build on
- Range Sum Query - Mutable
Range Updates and Sums (official problem, opens in a new tab)
Reveal learning notes #61
- What this teaches
- Range assignment and addition tags compose in different orders, so a single undifferentiated pending value is insufficient.
- Target approach
- Implement a lazy segment tree for sums with segment length, an explicit pending-assignment flag/value, and pending addition; derive tag composition in chronological order.
- Pattern coverage
- #61 Segment tree / lazy propagation
- Build on
- Dynamic Range Minimum Queries
Hotel Queries (official problem, opens in a new tab)
Reveal learning notes #61
- What this teaches
- Finding the first feasible index can descend a maximum segment tree rather than binary-searching with repeated queries.
- Target approach
- Store segment maxima, descend left first whenever its maximum can satisfy the request, and decrement the selected leaf.
- Pattern coverage
- #61 Segment tree / lazy propagation
- Build on
- Dynamic Range Minimum Queries
Static Range Minimum Queries (official problem, opens in a new tab)
Reveal learning notes #62
- What this teaches
- Static idempotent minimum queries permit overlapping precomputed blocks, while sum would double-count the overlap.
- Target approach
- Implement a sparse table and O(1) minimum queries using two covering power-of-two blocks; do not substitute a segment tree.
- Pattern coverage
- #62 Sparse table for static idempotent queries
Salary Queries (official problem, opens in a new tab)
Reveal learning notes #60, #63
- What this teaches
- Offline-known replacement values can all be compressed before processing dynamic frequency queries.
- Target approach
- Collect initial and update salaries for coordinate compression, then use Fenwick point-frequency changes and lower/upper bounds for inclusive value-range counts.
- Pattern coverage
- #60 Fenwick tree / binary indexed tree; #63 Coordinate compression
Distinct Values Queries (official problem, opens in a new tab)
Reveal learning notes #64
- What this teaches
- Ordering static queries by right endpoint lets one active marker per value represent distinctness in any queried suffix.
- Target approach
- Sort queries by right endpoint, move each value's Fenwick marker from its previous occurrence to its latest, and query interval sums; separately derive and compare Mo's add/remove alternative.
- Pattern coverage
- #64 Offline query ordering
- Build on
- Range Sum Query - Mutable
School Dance (official problem, opens in a new tab)
Reveal learning notes #72
- What this teaches
- A currently occupied partner may be reassigned along an augmenting path to increase the total matching.
- Target approach
- Implement augmenting-path bipartite matching and output the matched pairs; state its O(VE) bound and when Hopcroft-Karp is preferable.
- Pattern coverage
- #72 Matching / flow reduction
Download Speed (official problem, opens in a new tab)
Reveal learning notes #72
- What this teaches
- Multiple units of capacity require a residual network with reverse edges instead of one irreversible greedy path choice.
- Target approach
- Implement Dinic with residual capacities, level-graph BFS and blocking-flow DFS; use wide integers and handle parallel edges.
- Pattern coverage
- #72 Matching / flow reduction
- Build on
- School Dance
No matching problems. Try fewer search terms or reset the filters.
The 72-pattern coverage index
Open a pattern to find every assigned problem.A problem can cover several patterns when the learning notes explicitly require them. Supporting fundamentals may have no pattern number. Follow a problem link to clear filters and jump to its curriculum entry.
01Hash lookup and frequency15
- 001 Two SumCore
- 002 Group AnagramsCore
- 005 Subarray Sum Equals KCore
- 013 Contains DuplicateCore
- 014 Valid SudokuCore
- 021 Permutation in StringCore
- 022 Longest Substring Without Repeating CharactersCore
- 024 Minimum Window SubstringCore
- 025 Subarrays with K Different IntegersCore
- 050 Top K Frequent ElementsCore
- 121 Longest Consecutive SequenceReinforcement
- 124 Contiguous ArrayReinforcement
- 125 Subarray Sums Divisible by KReinforcement
- 132 Longest Repeating Character ReplacementReinforcement
- 153 Copy List with Random PointerReinforcement
02Opposite-end two pointers4
- 017 Two Sum II - Input Array Is SortedCore
- 018 3SumCore
- 019 Container With Most WaterCore
- 131 Trapping Rain WaterReinforcement
03Read-write pointers4
- 003 Remove Duplicates from Sorted ArrayCore
- 015 Move ZeroesCore
- 016 Sort ColorsCore
- 122 Merge Sorted ArrayReinforcement
04Fixed-size sliding window2
05Variable-size sliding window9
- 022 Longest Substring Without Repeating CharactersCore
- 023 Minimum Size Subarray SumCore
- 024 Minimum Window SubstringCore
- 025 Subarrays with K Different IntegersCore
- 132 Longest Repeating Character ReplacementReinforcement
- 133 Max Consecutive Ones IIIReinforcement
- 134 Count Number of Nice SubarraysReinforcement
- 137 Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitReinforcement
- 215 Find K-th Smallest Pair DistanceExtension
06Exactly k via at-most counts2
07Prefix aggregates4
- 004 Range Sum Query - ImmutableCore
- 123 Range Sum Query 2D - ImmutableReinforcement
- 156 Random Pick with WeightReinforcement
- 212 Shortest Subarray with Sum at Least KExtension
08Prefix sum plus hash map4
- 005 Subarray Sum Equals KCore
- 124 Contiguous ArrayReinforcement
- 125 Subarray Sums Divisible by KReinforcement
- 170 Path Sum IIIReinforcement
09Difference array2
- 006 Corporate Flight BookingsCore
- 140 Car PoolingReinforcement
10Kadane's maximum subarray2
- 007 Maximum SubarrayCore
- 126 Maximum Sum Circular SubarrayReinforcement
11Prefix-suffix composition2
- 008 Product of Array Except SelfCore
- 131 Trapping Rain WaterReinforcement
12Monotonic stack4
- 026 Daily TemperaturesCore
- 027 Largest Rectangle in HistogramCore
- 135 Sum of Subarray MinimumsReinforcement
- 136 Remove K DigitsReinforcement
13Monotonic deque3
14Stack for nested structure7
- 029 Valid ParenthesesCore
- 030 Evaluate Reverse Polish NotationCore
- 046 Min StackCore
- 138 Decode StringReinforcement
- 139 Asteroid CollisionReinforcement
- 157 Flatten Nested List IteratorReinforcement
- 213 Basic CalculatorExtension
15Binary search for a boundary8
- 031 Binary SearchCore
- 032 Find First and Last Position of Element in Sorted ArrayCore
- 033 Search in Rotated Sorted ArrayCore
- 034 Search a 2D MatrixCore
- 141 Find Minimum in Rotated Sorted ArrayReinforcement
- 142 Search in Rotated Sorted Array IIReinforcement
- 156 Random Pick with WeightReinforcement
- 214 Median of Two Sorted ArraysExtension
16Binary search on the answer4
17Sort and merge intervals3
- 037 Merge IntervalsCore
- 146 Insert IntervalReinforcement
- 147 Interval List IntersectionsReinforcement
18Sweep line and events3
- 038 Restaurant CustomersCore
- 140 Car PoolingReinforcement
- 216 The Skyline ProblemExtension
19Heap for top k4
20Heap for k-way merge3
21Two heaps for a median2
22Quickselect2
- 049 Kth Largest Element in an ArrayCore
- 158 K Closest Points to OriginReinforcement
23Fast-slow pointers5
- 039 Linked List CycleCore
- 042 Reorder ListCore
- 148 Linked List Cycle IIReinforcement
- 149 Find the Duplicate NumberReinforcement
- 151 Palindrome Linked ListReinforcement
24Linked-list reversal5
- 040 Reverse Linked ListCore
- 042 Reorder ListCore
- 150 Reverse Linked List IIReinforcement
- 151 Palindrome Linked ListReinforcement
- 217 Reverse Nodes in k-GroupExtension
25DFS / flood fill12
- 062 Invert Binary TreeCore
- 063 Same TreeCore
- 069 Construct Binary Tree from Preorder and Inorder TraversalCore
- 070 Serialize and Deserialize Binary TreeCore
- 073 Path SumCore
- 074 Number of IslandsCore
- 075 Clone GraphCore
- 076 Surrounded RegionsCore
- 077 Pacific Atlantic Water FlowCore
- 164 Symmetric TreeReinforcement
- 170 Path Sum IIIReinforcement
- 175 Evaluate DivisionReinforcement
26BFS / multi-source BFS8
- 060 Binary Tree Level Order TraversalCore
- 070 Serialize and Deserialize Binary TreeCore
- 078 Rotting OrangesCore
- 079 Word LadderCore
- 171 01 MatrixReinforcement
- 172 Shortest Path in a Grid with Obstacles EliminationReinforcement
- 187 Shortest Path to Get All KeysReinforcement
- 241 Shortest Path Visiting All NodesExtension
270–1 BFS1
28Dijkstra's shortest paths4
- 080 Network Delay TimeCore
- 173 Path With Minimum EffortReinforcement
- 174 Path with Maximum ProbabilityReinforcement
- 235 Flight DiscountExtension
29Bellman–Ford2
- 081 Cheapest Flights Within K StopsCore
- 227 Cycle FindingExtension
30Floyd–Warshall1
31Topological ordering / DAG DP5
32Union–find / disjoint-set union5
33Minimum spanning tree2
34Bipartite coloring1
35DFS cycle states / strongly connected components3
- 082 Course ScheduleCore
- 176 Find Eventual Safe StatesReinforcement
- 231 Planets and KingdomsExtension
36Tree postorder DP6
- 061 Maximum Depth of Binary TreeCore
- 064 Balanced Binary TreeCore
- 065 Diameter of Binary TreeCore
- 066 Binary Tree Maximum Path SumCore
- 165 House Robber IIIReinforcement
- 166 Sum of Distances in TreeReinforcement
37BST ordering / inorder traversal5
- 067 Validate Binary Search TreeCore
- 068 Kth Smallest Element in a BSTCore
- 167 Binary Search Tree IteratorReinforcement
- 168 Delete Node in a BSTReinforcement
- 169 Lowest Common Ancestor of a Binary Search TreeReinforcement
38LCA / binary lifting4
39Memoization / one-dimensional DP8
- 095 Longest Increasing Path in a MatrixCore
- 096 Climbing StairsCore
- 097 House RobberCore
- 098 Maximum Product SubarrayCore
- 099 Decode WaysCore
- 100 Word BreakCore
- 188 House Robber IIReinforcement
- 198 Number of Longest Increasing SubsequenceReinforcement
40Grid DP6
- 101 Unique PathsCore
- 102 Minimum Path SumCore
- 103 Maximal SquareCore
- 189 Unique Paths IIReinforcement
- 190 Dungeon GameReinforcement
- 191 Cherry Pickup IIReinforcement
410/1 knapsack / subset sum3
- 104 Partition Equal Subset SumCore
- 105 Target SumCore
- 192 Ones and ZeroesReinforcement
42Unbounded knapsack / coin change3
- 106 Coin ChangeCore
- 107 Coin Change IICore
- 193 Combination Sum IVReinforcement
43Two-sequence DP: LCS / edit distance5
- 108 Longest Common SubsequenceCore
- 109 Edit DistanceCore
- 194 Distinct SubsequencesReinforcement
- 195 Interleaving StringReinforcement
- 196 Regular Expression MatchingReinforcement
44Longest increasing subsequence: tails3
- 110 Longest Increasing SubsequenceCore
- 197 Russian Doll EnvelopesReinforcement
- 198 Number of Longest Increasing SubsequenceReinforcement
45Interval DP3
- 111 Longest Palindromic SubsequenceCore
- 199 Burst BalloonsReinforcement
- 200 Minimum Cost to Cut a StickReinforcement
46Bitmask DP5
- 187 Shortest Path to Get All KeysReinforcement
- 239 Can I WinExtension
- 240 Minimum XOR Sum of Two ArraysExtension
- 241 Shortest Path Visiting All NodesExtension
- 242 Hamiltonian FlightsExtension
47Digit DP1
- 243 Count Special IntegersExtension
48Finite-state DP: stock / cooldown7
- 097 House RobberCore
- 098 Maximum Product SubarrayCore
- 112 Best Time to Buy and Sell Stock with CooldownCore
- 165 House Robber IIIReinforcement
- 188 House Robber IIReinforcement
- 201 Best Time to Buy and Sell Stock with Transaction FeeReinforcement
- 202 Best Time to Buy and Sell Stock IVReinforcement
49Backtracking and pruning13
- 088 SubsetsCore
- 089 PermutationsCore
- 090 Combination SumCore
- 091 Generate ParenthesesCore
- 094 Word SearchCore
- 177 Subsets IIReinforcement
- 178 Permutations IIReinforcement
- 179 Combination Sum IIReinforcement
- 180 N-QueensReinforcement
- 181 Palindrome PartitioningReinforcement
- 182 Word Break IIReinforcement
- 184 Word Search IIReinforcement
- 236 Sudoku SolverExtension
50Greedy choice with an exchange proof7
- 054 Non-overlapping IntervalsCore
- 055 Jump GameCore
- 056 Jump Game IICore
- 057 Partition LabelsCore
- 160 Gas StationReinforcement
- 161 CandyReinforcement
- 162 Course Schedule IIIReinforcement
51Greedy scheduling with a heap4
- 058 Room AllocationCore
- 059 Maximum Number of Events That Can Be AttendedCore
- 162 Course Schedule IIIReinforcement
- 163 Meeting Rooms IIIReinforcement
52Meet in the middle3
- 183 Closest Subsequence SumReinforcement
- 237 Partition Array Into Two Arrays to Minimize Sum DifferenceExtension
- 238 Meet in the MiddleExtension
53Trie / prefix tree5
- 092 Implement Trie (Prefix Tree)Core
- 093 Design Add and Search Words Data StructureCore
- 184 Word Search IIReinforcement
- 185 Search Suggestions SystemReinforcement
- 186 Maximum XOR of Two Numbers in an ArrayReinforcement
54KMP / Z-function matching4
- 113 Find the Index of the First Occurrence in a StringCore
- 203 Longest Happy PrefixReinforcement
- 204 Shortest PalindromeReinforcement
- 246 String MatchingExtension
55Rolling hash for substring queries1
- 223 Longest Duplicate SubstringExtension
56Palindrome centers / palindrome DP3
57XOR, bit masks, and bit counts10
- 116 Single NumberCore
- 117 Number of 1 BitsCore
- 118 Counting BitsCore
- 128 Game of LifeReinforcement
- 186 Maximum XOR of Two Numbers in an ArrayReinforcement
- 187 Shortest Path to Get All KeysReinforcement
- 205 Single Number IIIReinforcement
- 206 Single Number IIReinforcement
- 236 Sudoku SolverExtension
- 241 Shortest Path Visiting All NodesExtension
58GCD and modular arithmetic5
- 119 Greatest Common Divisor of StringsCore
- 207 ExponentiationReinforcement
- 244 Fibonacci NumbersExtension
- 245 Graph Paths IExtension
- 247 Binomial CoefficientsExtension
59Sieve and divisor preprocessing2
- 208 Count PrimesReinforcement
- 248 Counting DivisorsExtension
60Fenwick tree / binary indexed tree5
- 120 Range Sum Query - MutableCore
- 209 Count of Smaller Numbers After SelfReinforcement
- 224 Subtree QueriesExtension
- 249 List RemovalsExtension
- 254 Salary QueriesExtension
61Segment tree / lazy propagation3
- 250 Dynamic Range Minimum QueriesExtension
- 251 Range Updates and SumsExtension
- 252 Hotel QueriesExtension
62Sparse table for static idempotent queries1
- 253 Static Range Minimum QueriesExtension
63Coordinate compression2
- 209 Count of Smaller Numbers After SelfReinforcement
- 254 Salary QueriesExtension
64Offline query ordering2
- 210 Checking Existence of Edge Length Limited PathsReinforcement
- 255 Distinct Values QueriesExtension
65Euler tour tree flattening1
- 224 Subtree QueriesExtension
66Rerooting tree DP2
- 166 Sum of Distances in TreeReinforcement
- 225 Tree Distances IExtension
67Expanded-state graph search4
- 172 Shortest Path in a Grid with Obstacles EliminationReinforcement
- 187 Shortest Path to Get All KeysReinforcement
- 235 Flight DiscountExtension
- 241 Shortest Path Visiting All NodesExtension
68Reverse reasoning / reverse graph3
- 077 Pacific Atlantic Water FlowCore
- 176 Find Eventual Safe StatesReinforcement
- 232 Bricks Falling When HitExtension
69Matrix / transition exponentiation2
- 244 Fibonacci NumbersExtension
- 245 Graph Paths IExtension
70Merge-sort counting / divide and conquer3
- 012 Sort an ArrayCore
- 127 Reverse PairsReinforcement
- 211 Count of Range SumExtension
71Composite structures for operation guarantees8
- 044 LRU CacheCore
- 045 Insert Delete GetRandom O(1)Core
- 046 Min StackCore
- 047 Implement Queue using StacksCore
- 154 Insert Delete GetRandom O(1) - Duplicates allowedReinforcement
- 155 LFU CacheReinforcement
- 157 Flatten Nested List IteratorReinforcement
- 218 All O`one Data StructureExtension
72Matching / flow reduction2
- 256 School DanceExtension
- 257 Download SpeedExtension
Can you recognize it without the label?
These checkpoints are intentionally shown as a mixed, title-only list. Reserve them until the relevant foundations are familiar. If you already saw a solution or its learning note, use a fresh related problem for your next blind assessment.
- Cheapest Flights Within K Stops (official problem, opens in a new tab)
- Koko Eating Bananas (official problem, opens in a new tab)
- Distinct Subsequences (official problem, opens in a new tab)
- Random Pick with Weight (official problem, opens in a new tab)
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (official problem, opens in a new tab)
- Accounts Merge (official problem, opens in a new tab)
- Linked List Cycle II (official problem, opens in a new tab)
- Target Sum (official problem, opens in a new tab)
- Pacific Atlantic Water Flow (official problem, opens in a new tab)
- K Closest Points to Origin (official problem, opens in a new tab)
- Partition Labels (official problem, opens in a new tab)
What counts as mastery?
Judge the performance, not the submission count.Independent
From a blank editor, explain a suitable method, justify why it works, implement it without solution help, test it, and meet the required complexity.
Retained
Repeat from a blank editor after at least a week without reading your old code. Explain the invariant rather than recalling line order.
Transfer
Solve an unfamiliar related problem with its topic label hidden, or handle a changed constraint and justify the new method.
Interview-ready evidence
Across several mixed timed sessions, clarify requirements, derive an approach, communicate tradeoffs, write correct code, and debug independently. A completed list alone cannot establish this.
Use a mix of fresh problems and the blind checkpoint set. Aim to complete several 45-60 minute sessions containing one substantial problem or two shorter ones without hints, including explanation and tests. Diagnose repeated gaps by pattern and revisit those modules. The timing is a practice design, not a claim about every employer.
A productive study session
- Before coding: identify the output, structure, constraints, brute-force cost, candidate patterns, and the property that permits improvement.
- Attempt a Core problem for roughly 25-40 focused minutes before seeking a small hint. Harder Reinforcement or Extension work can take longer; these are study timeboxes, not universal interview limits.
- If stuck, name the missing step and reveal the smallest useful hint. Reading a full solution counts as Learning, even when the later submission passes.
- After coding: state time and space, test adversarial cases, and record the failed assumption or implementation mistake.
- Rebuild on a later day, then revisit after about a week. Adjust intervals to your recall; the tracker uses an editable review interval.
- For each technique, change one property: allow negatives, require a witness, add updates, permit duplicate values, or switch from counting to optimization.
How these problems were selected
- Select an anchor for each method, then a variation that changes a constraint, output, state, or invariant.
- Keep additional problems only when they teach a distinct implementation or reasoning skill. Count each canonical problem once even if it covers several patterns.
- Prescribe the learning approach where multiple valid algorithms exist. A judge acceptance using another method does not prove coverage of the assigned pattern.
- Prefer problems whose statements are available without a paid subscription. Platform access and editorial availability can change independently.
- Separate specialist extensions from the general interview path. Tier and order are editorial judgments, not measured company-frequency rankings.
Implementation checks
- Implement lower_bound and upper_bound with explicit interval invariants.
- Implement an iterative traversal, BFS with path reconstruction, and heap-based Dijkstra with stale-entry handling.
- Implement DSU with union by size/rank and path compression; explain why DSU parents are not graph paths.
- Implement and test a heap, trie, linked-list reversal, and an LRU cache using the appropriate primitives.
- Derive a DP state and recurrence before choosing memoization, tabulation, or space compression.
- For full specialist coverage, implement a Fenwick tree, lazy segment tree, sparse table, KMP, and one matching algorithm.
Questions that test transfer
- Sliding window
- What changes if values may be negative, or if the window must contain exactly k distinct values?
- Prefix sums
- Does the query ask for a count, a longest interval, or a shortest interval? What must each prefix-map entry store?
- Binary search
- What makes the predicate monotone, what are the bounds, and what happens when no feasible value exists?
- Monotonic structures
- Why is a removed candidate permanently dominated? Which equality rule and expiration rule are correct?
- Graphs
- Do weights, direction, cycles, or resources change the search method or the definition of a state?
- Trees
- Is the answer for one subtree, one path, one root, or every possible root?
- Dynamic programming
- Which histories may share a state? Does loop order allow reuse or change whether order is counted?
- Greedy
- What exchange or dominance argument proves the choice safe? What weighted variant breaks it?
- Data-structure design
- What must be synchronized across structures? Are complexity guarantees expected, amortized, or worst-case?
- Strings and ranges
- Do queries require exactness, updates, prefix structure, or a particular algebraic property?