DSA & Dynamic Programming
Data structures, algorithm patterns, decision ladders, 16 code templates in Python and Java, graph algorithms, every DP family and a filterable 434-problem bank.
00DSA atlas — topics, patterns & routes
Use this as the table of contents and routing map. The following sections hold the detailed templates, diagrams, and problem references.
Complete DSA topic map#
Follow the anchors below for the detailed coverage already in this sheet: arrays/search/windows §03 · pattern templates §04 · core recipes §06 · trees/strings/bits §07 · graphs §08 · DP §09 · recursion/backtracking §11 §12 · range structures §13 · practice lookup §15.
Route from the question to a pattern#
flowchart LR
S[Read constraints and required output] --> Q{{What kind of answer?}}
Q -->|position, pair, rank| O{{Sorted or monotone?}}
O -->|yes| BS[Binary search or two pointers]
O -->|no| H[Hash map or sort then scan]
Q -->|contiguous range| C{{Window validity is monotone?}}
C -->|yes| W[Sliding window]
C -->|no: signed values or exact sum| P[Prefix sum plus hashmap or prefix deque]
Q -->|range aggregate| R[Choose static, updates, or offline query tool]
Q -->|next/previous greater or window extrema| M[Monotonic stack or deque]
Q -->|enumerate every construction| BT[Backtracking with choose / undo]
Q -->|best or count over choices| D{{Repeated states?}}
D -->|yes| DP[Dynamic programming]
D -->|no| G[Prove a greedy choice or use search]
Q -->|reachability, path, dependency| GR[Graph / grid traversal or graph algorithm]
Q -->|pattern, prefix, palindrome| ST[String matching / trie / palindrome tool]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,O,C,D decBefore coding, state the invariant or DP state, prove why the next step is safe, then check complexity against the constraints.
Check yourself 2 questions
Position, pair or rank question on sorted input: which family?
Show answer
Binary search or two pointers.
Same question on unsorted input?
Show answer
A hash map (or sort first if allowed).
Takeaway Read constraints and the answer shape first; sortedness, contiguity and structure point to the pattern.
Range-query route#
flowchart TD
S[Many queries on ranges?] --> U{{Are values updated?}}
U -->|no| K{{Aggregate}}
K -->|sum / count| PR["Prefix sums: O(1) query"]
K -->|min max gcd| SP["Sparse table: O(1) for idempotent ops"]
K -->|range update, point read| DF[Difference array]
U -->|point updates| P{{Aggregate}}
P -->|sum / frequency / prefix search| F[Fenwick tree]
P -->|general combine or point min/max| SG[Segment tree]
U -->|range updates| LA[Lazy segment tree]
U -->|offline queries, reorder allowed| MO[Mo's algorithm or sort-and-sweep]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class U,K,P decCheck yourself 2 questions
Static range sums: which structure?
Show answer
Prefix sums, O(1) per query.
Static range min with many queries?
Show answer
A sparse table, O(1) per query.
Takeaway No updates: prefix sums for sums, sparse table for idempotent min/max; with updates: Fenwick or segment tree.
Coverage map — where each family lives#
| Family | Patterns covered here | Jump |
|---|---|---|
| Arrays & search | Hashing, prefix/suffix, two pointers, windows, binary search, sorting, selection, intervals | §03 · §04 · §06 |
| Linear structures | Linked-list pointers, stack/queue, monotonic stack/deque, heap | §03 · §06 |
| Trees & connectivity | Traversals, BST, LCA, tree DP, trie, DSU | §03 · §07 |
| Graphs | BFS/DFS, cycles, topo/DAG, shortest paths, MST, SCC, bridges, articulation points | §08 |
| Choices & optimization | Greedy, recursion, backtracking, pruning, DP state families | §11 · §12 · §09 |
| Strings, bits & math | Tries, KMP, Z, rolling hash, palindromes, bit tricks, sieve and number theory | §03 · §07 |
| Range data structures | Fenwick/BIT and advanced structure triggers | §13 · §0 range route |
Check yourself 2 questions
Which families sit under arrays and search?
Show answer
Hashing, prefix/suffix, two pointers, windows, binary search, sorting, selection, intervals.
What is the coverage map for?
Show answer
Jumping to the section that covers a family.
Takeaway The coverage map shows where each pattern family lives on the sheet.
Advanced pattern triggers to complete the map#
| Signal | Technique family | Recognition rule |
|---|---|---|
| Range queries plus updates | Fenwick, segment tree, lazy propagation, sparse table | Choose by update type and whether the operation is associative/idempotent; see the range route above. |
| Ranks, kth value, or many distinct values | Coordinate compression + Fenwick/order-statistics structure | Map values to dense ranks, then maintain counts or prefix frequencies. |
| Offline range queries | Mo's algorithm, sweep line, divide-and-conquer | Use when queries can be reordered and moving a range boundary is cheap. |
| Many patterns in one text | Aho–Corasick | Trie of patterns + failure links; scan the text once. |
| Many suffix or substring comparisons | Suffix array + LCP, suffix automaton | Use when repeated substring queries outgrow rolling hash or a suffix trie. |
| Shortest paths with special structure | DAG relaxation, 0–1 BFS, bidirectional BFS, A* | Exploit acyclicity, binary weights, two endpoints, or a useful heuristic. |
| Network flow / one-to-one matching | Max flow (Dinic), bipartite matching | Model capacities or alternating paths; min cut gives a certificate. |
| Large choice set with n around 40 | Meet in the middle | Split the choices, enumerate each half, then combine sorted sums or states. |
| One answer for every root / digit constraints | Rerooting DP / digit DP | Choose a state that summarizes what a parent or prefix contributes. |
| Geometric ordering / hull / random stream | Sweep line, convex hull, reservoir sampling | Sort events or points by a coordinate; use randomized sampling when a stream cannot be stored. |
Check yourself 2 questions
Range queries plus updates suggest which family?
Show answer
Fenwick, segment tree with lazy propagation, or sparse table.
How do you choose among them?
Show answer
By update type and whether the operation is associative or idempotent.
Takeaway Range queries with updates, advanced graphs and advanced DP each have recognisable triggers.
One reusable solve flow#
Constraints → answer shape → invariant/state → data structure or recurrence → proof → complexity → edge-case dry run. Name the brute-force route first; each optimization should remove a repeated scan, repeated state, or unnecessary choice.
Check yourself 2 questions
What should you name before optimising?
Show answer
The brute-force route.
What should each optimisation remove?
Show answer
A repeated scan or repeated work.
Takeaway Constraints, answer shape, invariant, structure or recurrence, proof, complexity, edge-case dry run.
01Interview playbook & constraints
Coding/00-start-here/L3_CHEATSHEET.md
45-min coding round at the SDE II bar#
| Min | Do |
|---|---|
| 0–5 | Clarify: input size, sorted?, negatives?, duplicates?, empty? return format |
| 5–15 | Brute force → say Big-O → optimise; name the pattern aloud |
| 15–35 | Code clean; helper fns; meaningful names |
| 35–45 | Dry-run on example + edge case; state time/space |
SDE II bar: reach the optimal approach largely unprompted, finish a medium in about 25 minutes with clean, runnable code, test it yourself without being asked, and handle a follow-up (scale, streaming input, a constraint change). For a hard problem, a correct optimal plan with most of the code is usually a pass; silent coding is not. Full round-by-round expectations are on the Interview Prep sheet.
Check yourself 2 questions
What happens in the first 5 minutes?
Show answer
Clarify: input size, sortedness, negatives, duplicates, empty input, return format.
What does the SDE II bar add to a coding round?
Show answer
Optimal approach largely unprompted, a medium solved in about 25 minutes with clean runnable code, self-testing, and handling a follow-up.
Takeaway Clarify 5 min, brute force then optimise to 15, code to 35, test and discuss to 45.
Constraint → target complexity#
| N | Target | Typical |
|---|---|---|
| ≤10 | O(N!) | permutations, brute backtracking |
| ≤20 | O(2^N) | subsets, bitmask DP |
| ≤500 | O(N³) | Floyd, interval DP |
| ≤2000 | O(N²) | 2D DP, pairs |
| ≤10^5 | O(N log N) | sort, heap, binary search |
| 10^5–10^6 | O(N) | two-pointer, hash, sliding window |
| ≥10^9 | O(log N) | binary search on answer, math |
Check yourself 2 questions
N ≤ 10^5: target complexity?
Show answer
O(N log N).
N ≤ 20 suggests what?
Show answer
O(2^N): subsets or bitmask DP.
Takeaway N sets the target: ≤20 exponential, ≤500 cubic, ≤2000 quadratic, ≤10^5 n log n, larger linear.
Advanced patterns — use the atlas triggers#
- Range queries: Fenwick, segment tree/lazy, sparse table, offline Mo and sweep-line
- Advanced graphs: DAG paths, SCC, bridges/cut vertices, matching and max flow
- Advanced DP/search: bitmask, digit, tree/rerooting, meet-in-the-middle
- Advanced strings/math: Aho–Corasick, suffix structures, geometry and randomized methods
- Use the atlas triggers to choose the family; the later sections give the core templates and failure checks.
Common mistakes
- Off-by-one in binary search (
lo<=hivslo<hi) - Mutating list while iterating; shared default args
def f(a=[]) - Forgetting visited in graphs; recursion limit (
sys.setrecursionlimit) - Integer overflow in mid (Java/C++):
lo+(hi-lo)/2 - Copy path in backtracking:
res.append(path[:])
Check yourself 2 questions
Name two advanced graph topics.
Show answer
Any two of: DAG paths, SCCs, bridges and cut vertices, matching, max flow.
Name two advanced DP types.
Show answer
Any two of: bitmask, digit, tree, interval DP.
Takeaway Range queries, advanced graphs and advanced DP each map to a family via atlas triggers.
Complexity analysis toolkit#
- Amortised: dynamic array append O(1) (doubling), two-stack queue O(1), union-find ≈ O(α(n)), monotonic stack O(n) total because each item is pushed and popped once.
- Recursion space = max depth × frame size; memo tables add the state count.
- Backtracking: branching^depth × work per node (subsets 2ⁿ·n, permutations n!·n).
- Graph: adjacency list O(V+E) space; BFS/DFS O(V+E); Dijkstra O((V+E) log V).
- Strings: slicing and concatenation in a loop are O(n) each → O(n²) total; use a list and join.
- Hash maps: O(1) average, O(n) worst case; sorting is the safe O(n log n) alternative.
Check yourself 2 questions
T(n) = 2T(n/2) + O(n)?
Show answer
Θ(n log n).
T(n) = 2T(n/2) + O(1)?
Show answer
Θ(n).
Takeaway The master theorem compares f(n) with n^(log_b a); amortised and recursion-tree analysis cover the rest.
02Keyword decision guide
Coding/00-start-here/L3_CHEATSHEET.md, Coding/03-patterns/patterns-master.md
Keyword → pattern#
| If you see… | Think |
|---|---|
| sorted array, pair/target | Two pointers / binary search |
| contiguous subarray/substring, longest/shortest | Sliding window (positives only!) |
| subarray sum = k, negatives allowed | Prefix sum + hashmap {0:1} |
| top-K / K-th / stream median | Heap (size K) / two heaps |
| next greater / smaller, span, histogram | Monotonic stack |
| min/max that satisfies condition | Binary search on answer |
| all combinations / permutations / subsets | Backtracking |
| shortest path unweighted / grid | BFS (0-1 BFS if weights 0/1) |
| weighted shortest path | Dijkstra (non-neg) / Bellman-Ford (neg) |
| dependencies / order | Topo sort (Kahn) |
| connected groups, dynamic merging | Union-Find |
| overlapping intervals | Sort by start, merge / sweep |
| prefix strings / word dictionary | Trie |
| count ways / min cost / max value with choices | DP |
| linked list cycle / middle | Fast & slow pointers |
| max XOR pair | Bit trie |
Check yourself 2 questions
Subarray sum = k with negatives allowed?
Show answer
Prefix sums with a hash map.
Why is sliding window limited to positives for sums?
Show answer
Validity must be monotone as the window grows.
Takeaway Keywords map to patterns: sorted pair → two pointers, contiguous longest → window, subarray sum with negatives → prefix sums.
Decision flow#
flowchart TD
A[Problem] --> B{{Input sorted or can sort?}}
B -->|yes| C[Two pointers or Binary search]
B -->|no| D{{Contiguous range?}}
D -->|yes, positives| E[Sliding window]
D -->|yes, negatives| F[Prefix sum + hashmap]
D -->|no| G{{Graph or grid?}}
G -->|yes| H{{Weighted?}}
H -->|no| I[BFS / DFS]
H -->|yes| J[Dijkstra]
G -->|no| K{{Choices + optimal or count?}}
K -->|yes| L{{Overlapping subproblems?}}
L -->|yes| M[DP]
L -->|no| N[Greedy - prove exchange]
K -->|enumerate all| O[Backtracking]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class B,D,G,H,K,L decCheck yourself 2 questions
Contiguous range with only positive values?
Show answer
Sliding window.
Contiguous range with negatives?
Show answer
Prefix sums.
Takeaway Sorted → two pointers or binary search; contiguous → window or prefix sums; then structure-specific branches.
03“Which X?” decision trees (17 topics)
Coding/striver-a2z/*/README.md
Your own “Which X?” flowcharts from each striver-a2z topic README — one per topic.
Which array pattern, when 14-arrays#
Check yourself 2 questions
Maximum subarray sum?
Show answer
Kadane's algorithm.
Maximum subarray product: the extra trick?
Show answer
Track the minimum too, because negatives flip.
Takeaway Sorted → two pointers; contiguous max sum → Kadane; counting subarrays → prefix sums.
Which window? 22-sliding-window-and-2-pointer#
Check yourself 2 questions
How do you count windows with exactly K distinct?
Show answer
atMost(K) − atMost(K−1).
When doesn't a sliding window apply?
Show answer
When the subarray isn't contiguous or validity isn't monotone.
Takeaway Fixed k → add and drop; monotone validity → variable window; exactly K → atMost(K) − atMost(K−1).
Which binary search? 16-binary-search#
flowchart LR
S["Problem"] --> Q0{{Sorted / monotone input?}}
Q0 -->|"sorted array"| Q1{{Rotated?}}
Q1 -->|no| B["Bounds: lower_bound / upper_bound<br/>first & last occurrence, floor/ceil"]
Q1 -->|yes| R["Find the sorted half at each mid<br/>dups: lo++ hi-- when a[lo]=a[mid]=a[hi]"]
Q0 -->|"no, but a slope"| P["Peak: compare mid with mid+1"]
Q0 -->|"asked for a min/max value"| A{{Feasibility check monotone?}}
A -->|"min of max"| A1["first true: ans=mid, hi=mid-1"]
A -->|"max of min"| A2["last true: ans=mid, lo=mid+1"]
A -->|"real answer"| A3["100 fixed iterations"]
Q0 -->|"two sorted arrays, median/kth"| M["Partition the smaller array"]
Q0 -->|"matrix"| X{{Rows chain?}}
X -->|yes| X1["flattened index i/m, i%m"]
X -->|"rows+cols sorted"| X2["staircase from top-right"]
X -->|"rows only, median"| X3["BS on value + upper_bound count"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q0,Q1,A,X decCheck yourself 2 questions
Rotated sorted array: key observation?
Show answer
One half is always sorted; check which.
Minimise the maximum load: which binary search?
Show answer
Search on the answer with a monotone feasible(mid).
Takeaway Bounds for sorted arrays, a sorted-half check for rotated arrays, search on the answer for monotone feasibility.
Which stack/queue tool? 23-stack-and-queues#
Check yourself 2 questions
Next greater element: stack order?
Show answer
Decreasing.
Sliding window maximum?
Show answer
A monotonic deque.
Takeaway Nearest greater or smaller → monotonic stack; sums over subarray mins → contribution technique; window max → deque.
Which linked-list primitive? 19-linked-list#
flowchart LR
S["Linked-list problem"] --> Q1{{Head might change?}}
Q1 -->|yes| DH["Dummy head<br/>delete, merge, partition"]
S --> Q2{{Need a position<br/>without length?}}
Q2 -->|"middle"| MID["fast/slow<br/>fast and fast.next → 2nd middle"]
Q2 -->|"Nth from end"| GAP["fast ahead by N, then both"]
S --> Q3{{Cycle?}}
Q3 -->|"detect"| FL["Floyd: meet ⇒ cycle"]
FL -->|"start"| ST["reset one to head, step by 1"]
FL -->|"length"| LEN["one lap from meeting point"]
S --> Q4{{Order reversed / compare ends?}}
Q4 -->|yes| REV["iterative reverse<br/>palindrome, k-group, add"]
S --> Q5{{Sorted lists to combine?}}
Q5 -->|yes| MG["merge two → merge sort, flatten, k lists"]
S --> Q6{{Two lists share nodes?}}
Q6 -->|yes| SW["pointer switching a+c+b"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q1,Q2,Q3,Q4,Q5,Q6 decCheck yourself 2 questions
Finding the middle without the length?
Show answer
Fast and slow pointers.
When use a dummy head?
Show answer
When the head might change: delete, merge, partition.
Takeaway Dummy head when the head may change, fast/slow pointers for middle and cycles, in-place reversal for reordering.
Which binary-tree technique? 24-binary-trees#
Check yourself 2 questions
Diameter, height or max path sum: which traversal?
Show answer
Post-order, returning info upward.
Zigzag or level averages?
Show answer
BFS by level size.
Takeaway Answers needing both subtrees → post-order; per-level → BFS; paths from root → pre-order with state.
Which BST technique? 25-binary-search-trees#
flowchart LR
S["BST problem"] --> A{{"Looking for one value<br/>or its neighbour?"}}
A -->|exact| W["walk: compare, go one side<br/>(search, insert, LCA)"]
A -->|neighbour| C["walk + candidate<br/>(floor/ceil, pred/succ)"]
A -->|no| B{{"Needs sorted order?"}}
B -->|yes| I{{"Lazily / O(h) memory?"}}
I -->|yes| IT["stack of left spine<br/>(iterator, kth, two iterators for two-sum)"]
I -->|no| IN["inorder with prev<br/>(validate, recover swapped)"]
B -->|no| D{{"Change the tree?"}}
D -->|insert| INS["attach at the null slot"]
D -->|delete| DEL["0/1 child → child;<br/>2 children → successor copy / splice"]
D -->|build| PRE["preorder + upper bound, O(n)"]
D -->|no| PO["post-order (min, max, size)<br/>(largest BST subtree)"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class A,B,I,D decCheck yourself 2 questions
Floor in a BST?
Show answer
Walk down keeping the best candidate.
Kth smallest?
Show answer
Inorder traversal, which gives sorted order.
Takeaway Walk one side for search, insert and LCA; walk with a candidate for floor and ceil; inorder for sorted order and kth.
Which heap pattern? 26-heaps#
flowchart LR
S["Need repeated min / max<br/>of a changing set?"] --> A{{"What shape?"}}
A -->|"k largest / k-th largest"| K["min-heap of size k<br/>(root = answer)"]
A -->|"merge k sorted sources"| M["heap of (value, source, idx)<br/>pop → push next from same source"]
A -->|"running median"| T["two heaps: max-heap low half,<br/>min-heap high half, sizes differ ≤ 1"]
A -->|"always combine / process cheapest"| G["greedy min-heap<br/>(connect sticks, Huffman)"]
A -->|"most frequent / busiest first"| F["max-heap by count<br/>(task scheduler, reorganise)"]
A -->|"top-k of an implicit sorted grid"| L["best-first: pop, push neighbours,<br/>visited set (pair sums)"]
A -->|"sorted once, never updated"| X["just sort / quickselect"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class A decCheck yourself 2 questions
K largest elements: which heap and size?
Show answer
A min-heap of size k; the root is the kth largest.
Running median?
Show answer
A max-heap for the low half and a min-heap for the high half.
Takeaway K largest → min-heap of size k; merge k sorted → heap of heads; running median → two heaps.
Which greedy? 21-greedy-algorithms#
flowchart TD
S["Optimisation problem"] --> Q0{{"Does a counterexample<br/>break the local choice?"}}
Q0 -->|yes| DP["Use DP / search"]
Q0 -->|no| Q1{{Shape of input?}}
Q1 -->|"intervals / meetings"| I{{Goal?}}
I -->|"max non-overlapping / min removals"| I1["sort by END, keep compatible"]
I -->|"merge / insert"| I2["sort by START, extend last"]
I -->|"min rooms / platforms"| I3["sweep sorted starts & ends<br/>or min-heap of ends"]
Q1 -->|"items with value & weight"| K["sort by ratio v/w<br/>(fractional only)"]
Q1 -->|"jobs with deadlines"| J["profit desc + latest slot<br/>or deadline sort + min-heap"]
Q1 -->|"array reach / jumps"| R["track farthest reach;<br/>BFS windows for min jumps"]
Q1 -->|"two-sided neighbour constraint"| T["two passes: left, right, combine"]
Q1 -->|"match two lists"| M["sort both, two pointers"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q0,Q1,I decCheck yourself 2 questions
How do you check whether greedy is safe?
Show answer
Look for a counterexample that breaks the local choice.
Maximum non-overlapping intervals: sort by?
Show answer
End time.
Takeaway If a counterexample breaks the local choice, use DP; otherwise sort intervals by end, deadlines and so on.
Which bit trick? 20-bit-manipulation#
flowchart LR
S["Problem"] --> Q1{{What is asked?}}
Q1 -->|"read / write one bit"| A["mask = 1 << k<br/>test &, set |, clear & ~, toggle ^"]
Q1 -->|"count / power of 2"| B["n & (n − 1) clears lowest set bit"]
Q1 -->|"elements cancel in pairs"| C["XOR everything"]
C --> C1{{How many singles?}}
C1 -->|one| C2["XOR all"]
C1 -->|two| C3["XOR all → split by x & −x"]
Q1 -->|"appears k times"| D["count each bit mod k<br/>(k = 3: ones / twos)"]
Q1 -->|"all subsets, n ≤ 20"| E["masks 0 … 2ⁿ − 1"]
Q1 -->|"range XOR"| F["f(R) ^ f(L − 1), f by n mod 4"]
Q1 -->|"no * / %"| G["shift-and-subtract in 64-bit"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q1,C1 decCheck yourself 2 questions
What does n & (n − 1) do?
Show answer
Clears the lowest set bit.
Single number where every other appears twice?
Show answer
XOR everything.
Takeaway Masks for single bits, n & (n − 1) for counting and powers of two, XOR for cancelling pairs.
Which string technique? 17-strings-basic-medium#
Check yourself 2 questions
Balanced brackets of one type: need a stack?
Show answer
No, a depth counter is enough.
Roman numerals to integers trick?
Show answer
Subtract when a smaller value precedes a larger one.
Takeaway Depth counters for one bracket type, stacks for several, maps for symbol values, two pointers for mirrors.
Which string tool? 30-strings-advanced#
flowchart TD
S["String question"] --> Q{{"What is asked?"}}
Q -->|"find pattern in text"| P{{"Constraints"}}
P -->|"one pattern, exact output"| K["KMP or Z on pat#text"]
P -->|"many patterns, same length / substring equality"| H["Rolling hash (verify or double hash)"]
Q -->|"border / period / happy prefix"| L["lps[n−1], period = n − lps[n−1]"]
Q -->|"palindromic prefix"| R["lps of s#rev(s)"]
Q -->|"prefix match at every index"| Z["Z-function"]
Q -->|"tokens / runs"| T["two pointers, run-length scan"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,P decCheck yourself 2 questions
Find one pattern in text with exact output?
Show answer
KMP, or Z on pattern#text.
Many patterns at once?
Show answer
Aho-Corasick or a trie.
Takeaway One pattern → KMP or Z; many same-length patterns → rolling hash; many patterns → Aho-Corasick or a trie.
Which trie? 29-tries#
flowchart TD
S["Keys share prefixes?"] --> Q{{"Key type"}}
Q -->|"strings"| ST{{"What is asked?"}}
ST -->|"exists / prefix exists"| A["26-ary trie + end flag"]
ST -->|"how many words / prefixes, erase"| B["pass / end counters"]
ST -->|"all prefixes present"| C["walk: every node is an end"]
ST -->|"distinct substrings"| D["insert every suffix, count new nodes"]
Q -->|"integers, XOR"| BT["Binary trie, bits 30..0"]
BT --> E{{"Constraint per query?"}}
E -->|"none"| F["greedy opposite bit"]
E -->|"a ≤ m"| G["offline: sort queries by m, insert as you sweep"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,ST,E decCheck yourself 2 questions
Max XOR of a pair?
Show answer
A binary trie, greedily taking the opposite bit.
How do you support 'count words with prefix'?
Show answer
Store counts on trie nodes.
Takeaway 26-ary trie with end flags for strings; add counts for prefix counting and erase; binary tries for max XOR.
Which sort, when 13-sorting#
flowchart TD
S[Need to sort] --> Q1{{n small, ≤ ~20, or nearly sorted?}}
Q1 -->|yes| INS["Insertion sort<br/>O(n) best, stable, in place"]
Q1 -->|no| Q2{{"Need stability or a guaranteed O(n log n)?"}}
Q2 -->|yes| MS["Merge sort<br/>O(n log n) always, stable, O(n) extra"]
Q2 -->|"no, want in place and fast on average"| QS["Quick sort<br/>O(n log n) avg, O(n²) worst, O(log n) stack"]
S --> Q3{{Values are small integers?}}
Q3 -->|yes| CS["Counting / bucket sort<br/>O(n + k), not comparison-based"]
SEL["Selection sort: fewest swaps, n − 1"] -.-> NOTE["Selection and bubble: teaching only"]
BUB["Bubble sort: O(n) best with the swapped flag"] -.-> NOTE
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q1,Q2,Q3 decCheck yourself 2 questions
Nearly sorted small input?
Show answer
Insertion sort: O(n) best case.
Need stability and guaranteed O(n log n)?
Show answer
Merge sort.
Takeaway Insertion for tiny or nearly sorted, merge for stability or guaranteed n log n, quick in general, counting for small ranges.
Which string primitive? 11-basic-strings#
Check yourself 2 questions
Anagram check?
Show answer
A count array (int[26]).
Palindrome check?
Show answer
Two pointers from both ends.
Takeaway Mirror comparisons use two pointers; multiset questions use count arrays; windows handle substrings.
Which template? 08-basic-maths#
flowchart LR
Q[Number problem] --> D{{About its digits?}}
D -->|yes| DL["Digit loop: d = n % 10; n //= 10<br/>count · reverse · palindrome · max · Armstrong"]
D -->|no| F{{About its factors?}}
F -->|one number| SQ["√n pairing: i and n/i<br/>divisors · perfect · prime"]
F -->|all numbers ≤ n| SV["Sieve of Eratosthenes<br/>count primes"]
F -->|two numbers| EU["Euclid: gcd(a, b) = gcd(b, a % b)<br/>gcd · lcm = a / g * b"]
Q --> P{{Product of 1..n?}}
P -->|yes| FA["Running product, watch overflow<br/>factorial"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class D,F,P decCheck yourself 2 questions
Reverse a number's digits?
Show answer
Digit loop: d = n % 10; n //= 10.
Find all divisors efficiently?
Show answer
Loop i up to √n, adding i and n/i.
Takeaway Digit questions use a digit loop; factor questions loop to √n; primes use sieves.
Which prime tool? 31-maths#
Check yourself 2 questions
Primes in [L, R] with R up to 10^12?
Show answer
A segmented sieve.
Factorise many numbers fast?
Show answer
A smallest-prime-factor (SPF) table.
Takeaway One number → trial division to √x; a range up to 10^12 → segmented sieve; all up to 10^7 → Eratosthenes; factors → SPF table.
04Pattern templates — recognise · code · complexity · pitfalls · problems
practice/imp.md, monotonic.md, dfs.md, L3_MASTER_GUIDE.md, striver-a2z READMEs + per-problem ‘Approaches at a glance’
Two pointers (opposite ends / write pointer)#
| Recognise | Complexity |
|---|---|
| sorted array; pair/triplet sum; in-place rearrange; merge | O(n) after O(n log n) sort; O(1) space |
l, r = 0, len(a) - 1 while l < r: s = a[l] + a[r] if s == target: return [l, r] if s < target: l += 1 else: r -= 1Pitfalls
- 3-sum: sort, skip duplicate anchors and duplicate l/r after a hit
- Dutch flag: don't advance mid after swapping with high
- Write pointer for “move zeroes / remove dups” — order preserved
Representative problems (your striver notes: 14-arrays)
- Linear Search — Linear scan: return at the first match O(n)
- Largest Element — Single pass: track the running max O(n)
- Second Largest Element — One pass, top-2 tracking: demote first → second on a new max O(n)
- Maximum Consecutive Ones — Running streak: cnt++ on 1, cnt = 0 on 0 O(n)
- Left Rotate Array by One — Save first, shift, place: temp = nums[0]; shift left; nums[n−1] = temp O(n)
- Left Rotate Array by K Places — Three reversals: rev(0,k−1), rev(k,n−1), rev(0,n−1) O(n)
- Move Zeros to End — Two pointers (write index): swap each non-zero into position j O(n)
- Remove Duplicates from Sorted Array — Two pointers: i = last unique, j scans O(n)
Check yourself 2 questions
Complexity of two pointers after sorting?
Show answer
O(n) plus the O(n log n) sort, O(1) space.
What's a write pointer for?
Show answer
In-place rearranging, such as removing duplicates.
Takeaway Sorted arrays, pair or triplet sums and in-place rearranging: O(n) after sorting, O(1) space.
Sliding window (variable)#
| Recognise | Complexity |
|---|---|
| contiguous subarray/substring; longest/shortest/count; validity monotone (positives only) | O(n) — each index enters/leaves once |
l = 0 for r, x in enumerate(a): add(x) while invalid(): # shrink while invalid remove(a[l]); l += 1 best = max(best, r - l + 1) # count exactly K = atMost(K) - atMost(K-1)Pitfalls
- Negatives / exact sums break monotonicity → prefix sum + hashmap
- Count ≤K: add r − l + 1 per r
- Fixed window k: add a[r], drop a[r−k]
Representative problems (your striver notes: 22-sliding-window-and-2-pointer)
- Maximum Points You Can Obtain from Cards — Slide the split: start with k left cards, swap one left for one right k times O(k)
- Longest Substring Without Repeating Characters — Window with last-seen index (jump): l = max(l, last[c] + 1) O(n)
- Max Consecutive Ones III — Non-shrinking window: if zeros > k: move l once O(n)
- Fruit Into Baskets — Window with counts: shrink while > 2 keys O(n)
- Longest Substring With At Most K Distinct Characters — Window with counts and a distinct counter: shrink while distinct > k O(n)
- Longest Repeating Character Replacement — Window with a stale maxFreq: maxFreq only increases; shrink by one O(n)
- Minimum Window Substring — Window with a deficit counter: expand until need == 0, then shrink | O( | s | + | t )
- Minimum Window Subsequence — Forward match + backward shrink: find an end, walk back to the tightest start O(n·m)
Check yourself 2 questions
Why is a variable window O(n)?
Show answer
Each index enters and leaves the window once.
Required property?
Show answer
Validity must be monotone.
Takeaway Expand right, shrink left while invalid; each index enters and leaves once, so O(n).
Prefix sum + hashmap#
| Recognise | Complexity |
|---|---|
| “how many subarrays with sum k”, negatives allowed, XOR k, longest sum k | O(n) time, O(n) space |
seen = {0: 1}; prefix = 0; count = 0 for n in nums: prefix += n count += seen.get(prefix - k, 0) # query FIRST seen[prefix] = seen.get(prefix, 0) + 1Pitfalls
- Seed {0: 1} before iterating; query before update
- Longest variant: store FIRST index of each prefix, don't overwrite
Representative problems (your striver notes: 14-arrays)
- Two Sum — One-pass hash map: seen[value] = index; look up target − x first O(n)
- 3 Sum — Sort + two pointers: fix i; l = i + 1, r = n − 1; skip duplicates O(n²)
- 4 Sum — Sort + two fixed + two pointers: i, j loops with skips; l/r on the rest O(n³)
- Kadane's Algorithm: Maximum Subarray Sum — Kadane: cur = max(x, cur + x); best = max(best, cur) O(n)
Check yourself 2 questions
Why initialise seen with {0: 1}?
Show answer
To count subarrays starting at index 0 (the empty prefix).
Complexity?
Show answer
O(n) time, O(n) space.
Takeaway seen = {0: 1}; count += seen[prefix − k] counts subarrays summing to k, negatives allowed.
Binary search — bounds & on answer#
| Recognise | Complexity |
|---|---|
| sorted / rotated; min of max, max of min; monotone feasible(mid) | O(log range · cost(feasible)) |
lo, hi = LO, HI while lo < hi: mid = (lo + hi) // 2 if feasible(mid): hi = mid # first true else: lo = mid + 1 return lo # real answer: 100 fixed iterationsPitfalls
- Rotated with dups: lo++ hi-- when a[lo]=a[mid]=a[hi]
- Max-of-min: last true → ans=mid, lo=mid+1
- Matrix rows chain → flattened index i/m, i%m
Representative problems (your striver notes: 16-binary-search)
- Search X in Sorted Array — Iterative binary search: closed interval [lo, hi]; drop the half that can't hold target O(log n)
- Lower Bound — Binary search with an answer variable: nums[mid] ≥ x → ans = mid, go left; else go right O(log n)
- Upper Bound — Binary search: nums[mid] > x → ans = mid, go left; else go right O(log n)
- Search Insert Position — Lower bound: answer-variable binary search with ≥ O(log n)
- Floor and Ceil in Sorted Array — Two binary searches: floor: last nums[i] ≤ x · ceil: first nums[i] ≥ x O(log n)
- First and Last Occurrence — One search, two directions: on match record and continue left (first) or right (last) O(log n)
- Search in Rotated Sorted Array I — One pass: pick the sorted half: nums[lo] ≤ nums[mid] → left sorted; test range, else go right O(log n)
- Search in Rotated Sorted Array II — Rotated search with tie shrinking: if lo, mid, hi all equal: lo++, hi−−; else as in part I O(log n) average, O(n) worst
- Find Minimum in Rotated Sorted Array — Compare mid with hi: nums[mid] > nums[hi] → lo = mid + 1, else hi = mid; answer nums[lo] O(log n)
- Find Out How Many Times the Array Is Rotated — Index of minimum: nums[mid] > nums[hi] → lo = mid + 1, else hi = mid; return lo O(log n)
Check yourself 2 questions
When feasible(mid) is true, what moves?
Show answer
hi = mid.
Complexity of search on the answer?
Show answer
O(log range × cost of feasible).
Takeaway lo < hi with hi = mid when feasible finds the first true; complexity O(log range × check cost).
Monotonic stack / deque#
| Recognise | Complexity |
|---|---|
| next/prev greater/smaller; span; histogram; sum of subarray mins; window max | O(n) amortised |
stack = [] # stores indices for i, x in enumerate(arr): while stack and arr[stack[-1]] > x: # increasing stack j = stack.pop() # j just found its answer (NSE = i) stack.append(i)Pitfalls
- >= vs >: arr[top] >= x → next strictly smaller; > x → smaller-or-equal
- Contribution a[i]·(i − PSE)·(NSE − i): strict on one side, ≤ on the other
- Window max: deque of indices, pop front when out of window
Representative problems (your striver notes: 23-stack-and-queues)
- Next Greater Element — Monotonic stack, right to left: pop ≤ current, top is the answer, push current O(n)
- Next Greater Element - 2 — Monotonic stack over 2n: right-to-left from 2n−1, answer only for i < n O(n)
- Asteroid Collision — Stack of survivors: new left-mover fights right-moving tops O(n)
- Sum of Subarray Minimums — Contribution with previous/next smaller: arr[i]·(i − pse)·(nse − i) O(n)
- Remove K Digits — Monotonic stack: pop larger tops while k > 0, then trim O(n)
- Next Smaller Element — Monotonic stack, right to left: pop ≥ current, top is the answer, push O(n)
- Sliding Window Maximum — Monotonic deque of indices: pop expired front, pop smaller back, push, read front O(n)
- Trapping Rainwater — Two pointers: move the lower side; its running max decides its water O(n)
- Largest rectangle in a histogram — One pass, compute on pop: sentinel 0 at the end; area when a bar is popped O(n)
- Maximum Rectangles — Histogram per row + monotonic stack: update heights, run largest-rectangle per row O(R·C)
- Stock span problem — Stack of (price, span): pop ≤ price, add their spans O(1) amortised
- The Celebrity Problem — Single-candidate elimination: candidate = i whenever candidate knows i; then verify O(n)
Check yourself 2 questions
What does the stack store?
Show answer
Indices, so you can compute distances and spans.
Why is it O(n)?
Show answer
Each index is pushed and popped at most once.
Takeaway Keep indices in a monotonic stack; pop while the new value breaks the order; O(n) amortised.
Heap / priority queue#
| Recognise | Complexity |
|---|---|
| K-th / top-K; merge k sorted; running median; always process cheapest | O(n log k) |
import heapq h = [] for x in nums: heapq.heappush(h, x) if len(h) > k: heapq.heappop(h) # min-heap of size k return h[0] # k-th largestPitfalls
- Python is min-heap only — negate for max
- Two heaps: max-heap low half, min-heap high half, sizes differ ≤ 1
- Merge K: push (value, list_idx, elem_idx)
Representative problems (your striver notes: 26-heaps)
- Check if an array represents a min heap — Loop over internal nodes: for i < n/2: check both children O(n)
- K-th Largest element in an array — Quickselect (3-way partition): partition around pivot; recurse into the side holding index n−k O(n) expected
- Kth largest element in a stream of running integers — Min-heap of size k: push; pop while size > k; return root add O(log k)
- Sort K sorted array — Min-heap of size k+1: seed k+1; pop min to output, push next O(n log k)
- Merge K sorted Lists — Min-heap of heads: pop smallest head, append, push its next O(N log k)
- Replace elements by its rank in the array — Sort distinct values + hash map: rank[v] = index in sorted(set(arr)) + 1 O(n log n)
- Task Scheduler — Counting formula: max(T, (f−1)(n+1) + #tasks with freq f) O(T)
- Hand of Straights — Sorted distinct keys, batch groups: for x ascending: open c[x] groups at x O(n log n)
Check yourself 2 questions
Top-k complexity with a size-k heap?
Show answer
O(n log k).
Python's heapq is which kind of heap?
Show answer
A min-heap.
Takeaway Push and pop beyond k keeps the top-k in O(n log k).
Linked list: dummy, fast/slow, reverse#
| Recognise | Complexity |
|---|---|
| head may change; middle; Nth from end; cycle; palindrome | O(n), O(1) |
slow = fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next if slow is fast: # cycle slow = head while slow is not fast: slow, fast = slow.next, fast.next return slow # cycle startPitfalls
- Use a dummy head whenever head can change
- Intersection: pointer switching a+c+b
- Reverse: prev, cur, nxt — save next before relinking
Representative problems (your striver notes: 19-linked-list)
- Traversal in Linked List — Iterative walk: cur = head; while cur: visit; cur = cur.next O(n)
- Deletion of the Head of LL — Advance the head: tmp = head; head = head.next; free tmp O(1)
- Deletion of the Tail of LL — Walk to the second-last node: while cur.next.next: cur = cur.next; cur.next = null O(n)
- Deletion of the Kth Element of LL — Dummy node: dummy → head; step k − 1 from dummy; bypass O(k)
- Delete the Element with Value X — Dummy + search predecessor: prev from dummy until prev.next.val == x; bypass O(n)
- Insertion at the Head of LL — New node points at old head: node(x).next = head; return node O(1)
- Insertion at the Tail of LL — Walk to the tail: while cur.next: advance; cur.next = node(x) O(n)
- Insertion at the Kth Position of LL — Dummy + splice: step k − 1 from dummy; node.next = prev.next; prev.next = node O(k)
Check yourself 2 questions
Detect a cycle?
Show answer
Floyd's fast and slow pointers meet if there's a cycle.
Space complexity of these primitives?
Show answer
O(1).
Takeaway Dummy heads, fast/slow pointers and in-place reversal solve most list problems in O(n) and O(1) space.
Tree DFS: return value / global max#
| Recognise | Complexity |
|---|---|
| answer depends on both subtrees (height, diameter, max path, balanced) | O(n), O(h) stack |
best = [0] def dfs(node): if not node: return 0 l, r = dfs(node.left), dfs(node.right) best[0] = max(best[0], l + r) # spans node → update global return 1 + max(l, r) # only one branch goes upPitfalls
- Base case first: if not node
- Snapshot path[:] when saving root-to-leaf paths
- LCA: both sides non-None → current node
Representative problems (your striver notes: 24-binary-trees)
- Inorder Traversal — Iterative with explicit stack: push left spine; pop → visit → go right O(n)
- Preorder Traversal — Iterative stack: pop → visit → push right, push left O(n)
- Postorder Traversal — One stack + last visited: descend left; at top: go right unless right is done; else visit O(n)
- Level Order Traversal — BFS with level snapshot: for _ in range(len(q)): pop, record, push children O(n)
- Pre, Post, Inorder in one traversal — Stack of (node, state): state 1 pre→left · 2 in→right · 3 post→pop O(n)
- Maximum Depth in BT — Recursive postorder: 1 + max(L, R) O(n)
- Check if two trees are identical or not — Recursive lock-step: null checks, value check, recurse both sides O(min(n, m))
- Check for balanced binary tree — Bottom-up height with −1 sentinel: h = −1 if a child is −1 or | hl − hr | > 1 O(n)
- Diameter of Binary Tree — Single postorder pass: best = max(best, hl + hr); return 1 + max(hl, hr) O(n)
- Maximum path sum — Single postorder pass: g = val + max(0, gL, gR); best = max(best, val + max(0,gL) + max(0,gR)) O(n)
Check yourself 2 questions
Diameter: what does dfs return and what goes to the global?
Show answer
Returns height (one arm); the global takes left + right.
Stack space of tree DFS?
Show answer
O(h).
Takeaway Return what the parent needs, update a global with the best combination of both children.
BST walk / inorder#
| Recognise | Complexity |
|---|---|
| search, floor/ceil, kth, validate, iterator | O(h) walk, O(n) inorder |
def inorder(node): # sorted order if not node: return inorder(node.left); visit(node); inorder(node.right) # floor: walk; if node.val <= x: ans = node.val, go right else leftPitfalls
- Validate with (lo, hi) bounds, not just parent
- Two-sum in BST: two iterators (next / before)
- Delete with 2 children → successor
Representative problems (your striver notes: 25-binary-search-trees)
- Search in BST — Iterative walk: while cur and cur.val != val: step left/right O(h)
- Floor and Ceil in a BST — Single walk per side: right-step → floor candidate; left-step → ceil candidate O(h)
- Minimum and Maximum in BST — Spine walks: leftmost = min, rightmost = max O(h)
- Insert a given node in BST — Iterative: walk until the needed child is null, attach O(h)
- Delete a node in BST — Iterative, splice: find parent; replace child with helper(child) O(h)
- Kth Smallest and Largest element in BST — Iterative inorder, early stop: kth pop of inorder; kth pop of reverse inorder O(h + k)
- Check if a tree is a BST or not — Bounds recursion: valid(n, lo, hi): lo < n.val < hi, recurse with narrowed window O(n)
- LCA in BST — Iterative split: loop until p and q fall on different sides O(h)
Check yourself 2 questions
How do you validate a BST?
Show answer
Inorder must be strictly increasing (or pass min/max bounds).
Complexity of a BST search walk?
Show answer
O(h).
Takeaway Walks cost O(h); inorder gives sorted order in O(n).
Trie (dict shortcut)#
| Recognise | Complexity |
|---|---|
| prefix match, autocomplete, word search, max XOR (binary trie) | O(L) per op |
trie = {} for w in words: node = trie for ch in w: node = node.setdefault(ch, {}) node['$'] = True # end markerPitfalls
- Binary trie for XOR: bits 30..0, greedy opposite bit
- Distinct substrings: insert every suffix, count new nodes
Representative problems (your striver notes: 29-tries)
- Implement Trie (prefix tree) — Trie of child arrays: node = children[26] + end flag O(L) per op
- Implement Trie II (count and erase) — Trie with pass / end counters: pass++ along the path, end++ at the last node O(L) per op
- Longest word with all prefixes (complete string) — Trie: every node on the path is an end: insert all, then walk each word checking end O(Σ L)
- Number of distinct substrings in a string — Suffix trie, count new nodes: for each start i, walk/extend from root O(n²)
- Maximum XOR of two numbers in an array — Binary trie, greedy from MSB: insert bits 30..0; query takes the opposite bit when it exists O(31·n)
- Maximum XOR with an element from the array — Offline sort + binary trie sweep: sort queries by m; insert nums ≤ m before answering O((n + q) log + 31(n + q))
Check yourself 2 questions
How is a word's end marked in the dict trie?
Show answer
A special key such as '$'.
Complexity per insert or search?
Show answer
O(L), the word length.
Takeaway Nested dicts with an end marker make a quick trie; O(L) per operation.
Greedy & intervals#
| Recognise | Complexity |
|---|---|
| intervals/meetings; jobs with deadlines; reach/jumps; counterexample doesn't break the local choice | O(n log n) |
intervals.sort(key=lambda x: x[1]) # by END end, keep = float('-inf'), 0 for s, e in intervals: if s >= end: keep += 1; end = ePitfalls
- Merge/insert → sort by START; max non-overlap → sort by END
- Min rooms → sweep starts & ends or min-heap of ends
- Candy-type: two passes left/right
Representative problems (your striver notes: 21-greedy-algorithms)
- Assign Cookies — Sort + two pointers: advance cookie always, child when fed O(n log n + m log m)
- Lemonade Change — Counters with greedy change: track #5 and #10; for 20 use 10+5 first O(n)
- Fractional Knapsack — Sort by ratio, fill greedily: best v/w first; last item fractional O(n log n)
- Jump Game I — Greedy farthest reach: maxReach = max(maxReach, i + nums[i]) O(n)
- Shortest Job First — Sort + running time: sort; wait += elapsed; elapsed += b O(n log n)
- Job Sequencing Problem — Deadline sort + min-heap: keep the best ≤ d jobs in a heap O(n log n)
- N Meetings in One Room — Sort by end, pick compatible: if start > lastEnd: take it O(n log n)
- Non-overlapping Intervals — Sort by end, count keepers: keep if start ≥ lastEnd; answer n − kept O(n log n)
Check yourself 2 questions
Sort key for maximum non-overlapping intervals?
Show answer
The end time.
When is greedy valid?
Show answer
When no counterexample breaks the local choice.
Takeaway Sort intervals by end and keep each one that starts after the last kept end.
Bit manipulation#
| Recognise | Complexity |
|---|---|
| pairs cancel; power of 2; subsets n ≤ 20; appears k times | O(1) / O(2ⁿ·n) |
n & (n - 1) # clear lowest set bit x & -x # lowest set bit for mask in range(1 << n): ... # all subsetsPitfalls
- Two singles: XOR all, split by x & −x
- Appears 3 times: count each bit mod 3
- Range XOR: f(R) ^ f(L−1), f by n mod 4
Representative problems (your striver notes: 20-bit-manipulation)
- Check if the i-th Bit is Set — Left-shift mask: n & (1 << k) != 0 O(1)
- Check if a Number is Odd — AND with 1: n & 1 O(1)
- Check if a Number is Power of 2 — n & (n − 1): one set bit ⇔ clearing it gives 0 O(1)
- Count the Number of Set Bits — Brian Kernighan: n &= n − 1 until 0 O(popcount)
- Set the Rightmost Unset Bit — n: (n + 1) | +1 carries through trailing 1s into the lowest 0 O(1)
- Swap Two Numbers — XOR swap: a ^= b; b ^= a; a ^= b O(1)
- Minimum Bit Flips to Convert Number — XOR + Kernighan: popcount(start ^ goal) O(popcount)
- Single Number I — XOR everything: pairs cancel O(n)
Check yourself 2 questions
Isolate the lowest set bit?
Show answer
x & −x.
Enumerate all subsets of n items?
Show answer
Loop mask over range(1 << n).
Takeaway n & (n − 1) clears the lowest bit, x & −x isolates it, and masks enumerate subsets for n ≤ 20.
05Code templates in Python and Java
Sixteen interview-ready templates. Switch language on any card; the choice applies everywhere and is remembered. Each card says when to reach for it.
Binary search: lower bound and search on the answer#
Sorted data, or a yes/no check that flips once (minimise the max, smallest capacity that works).
def lower_bound(a, x): # first index with a[i] >= x lo, hi = 0, len(a) while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: lo = mid + 1 else: hi = mid return lo def min_feasible(lo, hi, ok): # smallest v in [lo, hi] with ok(v); ok is monotone while lo < hi: mid = (lo + hi) // 2 if ok(mid): hi = mid else: lo = mid + 1 return lo
static int lowerBound(int[] a, int x) { // first index with a[i] >= x int lo = 0, hi = a.length; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (a[mid] < x) lo = mid + 1; else hi = mid; } return lo; } static long minFeasible(long lo, long hi, LongPredicate ok) { while (lo < hi) { long mid = lo + (hi - lo) / 2; if (ok.test(mid)) hi = mid; else lo = mid + 1; } return lo; }
Check yourself 2 questions
What does lower_bound return?
Show answer
The first index with a[i] ≥ x.
Initial hi for lower_bound?
Show answer
len(a).
Takeaway lower_bound finds the first index with a[i] ≥ x; the same shape searches answers.
Two pointers on a sorted array#
Pairs or triples with a target sum, merging, removing duplicates in place.
def pair_with_sum(a, target): # a is sorted l, r = 0, len(a) - 1 while l < r: s = a[l] + a[r] if s == target: return l, r if s < target: l += 1 # need a bigger sum else: r -= 1 # need a smaller sum return None
static int[] pairWithSum(int[] a, int target) { // a is sorted int l = 0, r = a.length - 1; while (l < r) { int s = a[l] + a[r]; if (s == target) return new int[]{l, r}; if (s < target) l++; else r--; } return null; }
Check yourself 2 questions
Sum too small: which pointer moves?
Show answer
The left pointer moves right.
Name two uses.
Show answer
Any two of: pair or triple sums, merging, removing duplicates in place.
Takeaway Move the left pointer up when the sum is small, the right down when large.
Sliding window (variable size)#
Longest or shortest contiguous range that satisfies a constraint that can be repaired by shrinking.
def longest_at_most_k_distinct(s, k): count, best, left = {}, 0, 0 for right, ch in enumerate(s): count[ch] = count.get(ch, 0) + 1 while len(count) > k: # shrink until valid again c = s[left] count[c] -= 1 if count[c] == 0: del count[c] left += 1 best = max(best, right - left + 1) return best
static int longestAtMostKDistinct(String s, int k) { Map<Character, Integer> count = new HashMap<>(); int best = 0, left = 0; for (int right = 0; right < s.length(); right++) { count.merge(s.charAt(right), 1, Integer::sum); while (count.size() > k) { char c = s.charAt(left++); if (count.merge(c, -1, Integer::sum) == 0) count.remove(c); } best = Math.max(best, right - left + 1); } return best; }
Check yourself 2 questions
When do you shrink the window?
Show answer
While the window is invalid (more than k distinct).
What tracks the distinct characters?
Show answer
A count dictionary.
Takeaway Longest substring with at most k distinct: expand, then shrink while the count exceeds k.
Prefix sum + hash map#
Count or find subarrays with sum (or XOR) equal to k, including negative numbers.
def subarray_sum_k(nums, k): seen = {0: 1} # empty prefix total = ans = 0 for x in nums: total += x ans += seen.get(total - k, 0) seen[total] = seen.get(total, 0) + 1 return ans
static int subarraySumK(int[] nums, int k) { Map<Integer, Integer> seen = new HashMap<>(); seen.put(0, 1); // empty prefix int total = 0, ans = 0; for (int x : nums) { total += x; ans += seen.getOrDefault(total - k, 0); seen.merge(total, 1, Integer::sum); } return ans; }
Check yourself 2 questions
Does prefix sum + hash map handle negatives?
Show answer
Yes.
What's added to the answer at each step?
Show answer
seen[total − k].
Takeaway Count subarrays with sum or XOR equal to k using a running total and a counter of seen prefixes.
Monotonic stack: next greater element#
Nearest bigger/smaller to the left or right, stock span, histogram areas.
def next_greater(a): res, st = [-1] * len(a), [] # st holds indices; values decreasing for i, x in enumerate(a): while st and a[st[-1]] < x: res[st.pop()] = x # x is the answer for everything it beats st.append(i) return res
static int[] nextGreater(int[] a) { int[] res = new int[a.length]; Arrays.fill(res, -1); Deque<Integer> st = new ArrayDeque<>(); // indices, values decreasing for (int i = 0; i < a.length; i++) { while (!st.isEmpty() && a[st.peek()] < a[i]) res[st.pop()] = a[i]; st.push(i); } return res; }
Check yourself 2 questions
What's the default answer if no greater element exists?
Show answer
−1.
Stack order for next greater?
Show answer
Decreasing values.
Takeaway Keep a decreasing stack of indices; each new larger value answers everything it pops.
Heap: top K largest#
K largest or most frequent, K closest, streaming top-K: keep a min-heap of size K.
import heapq def top_k(nums, k): h = [] for x in nums: heapq.heappush(h, x) if len(h) > k: heapq.heappop(h) # drop the smallest return sorted(h, reverse=True) # O(n log k)
static List<Integer> topK(int[] nums, int k) { PriorityQueue<Integer> h = new PriorityQueue<>(); // min-heap for (int x : nums) { h.offer(x); if (h.size() > k) h.poll(); // drop the smallest } List<Integer> out = new ArrayList<>(h); out.sort(Collections.reverseOrder()); return out; }
Check yourself 2 questions
Why a min-heap for the K largest?
Show answer
Its root is the smallest of the K kept, easy to evict.
Name another use.
Show answer
K most frequent, K closest, or streaming top-K.
Takeaway A min-heap of size K keeps the K largest; pop whenever it exceeds K.
BFS: shortest path on a grid#
Unweighted shortest path, minimum steps, multi-source spread (seed the queue with every source).
from collections import deque def shortest_path(grid, start, goal): # grid[r][c] == 1 is a wall R, C = len(grid), len(grid[0]) dist = {start: 0} q = deque([start]) while q: r, c = q.popleft() if (r, c) == goal: return dist[(r, c)] for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 0 and (nr, nc) not in dist: dist[(nr, nc)] = dist[(r, c)] + 1 # mark when enqueued q.append((nr, nc)) return -1
static int shortestPath(int[][] g, int sr, int sc, int tr, int tc) { int R = g.length, C = g[0].length; int[][] dist = new int[R][C]; for (int[] row : dist) Arrays.fill(row, -1); Deque<int[]> q = new ArrayDeque<>(); dist[sr][sc] = 0; q.offer(new int[]{sr, sc}); int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}}; while (!q.isEmpty()) { int[] cur = q.poll(); if (cur[0] == tr && cur[1] == tc) return dist[tr][tc]; for (int[] d : dirs) { int nr = cur[0] + d[0], nc = cur[1] + d[1]; if (nr >= 0 && nr < R && nc >= 0 && nc < C && g[nr][nc] == 0 && dist[nr][nc] == -1) { dist[nr][nc] = dist[cur[0]][cur[1]] + 1; q.offer(new int[]{nr, nc}); } } } return -1; }
Check yourself 2 questions
Why BFS for unweighted shortest paths?
Show answer
It explores in order of distance.
How do you run multi-source BFS?
Show answer
Seed the queue with every source.
Takeaway BFS gives unweighted shortest paths; seed every source for multi-source spread.
Topological sort (Kahn's algorithm)#
Prerequisites, build order, course schedule; leftover nodes mean a cycle.
from collections import deque def topo_order(n, edges): # (u, v): u must come before v adj = [[] for _ in range(n)] indeg = [0] * n for u, v in edges: adj[u].append(v); indeg[v] += 1 q = deque(i for i in range(n) if indeg[i] == 0) order = [] while q: u = q.popleft(); order.append(u) for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) return order if len(order) == n else [] # [] means a cycle
static List<Integer> topoOrder(int n, int[][] edges) { List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); int[] indeg = new int[n]; for (int[] e : edges) { adj.get(e[0]).add(e[1]); indeg[e[1]]++; } Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i); List<Integer> order = new ArrayList<>(); while (!q.isEmpty()) { int u = q.poll(); order.add(u); for (int v : adj.get(u)) if (--indeg[v] == 0) q.offer(v); } return order.size() == n ? order : List.of(); // empty means a cycle }
Check yourself 2 questions
How does Kahn's algorithm detect a cycle?
Show answer
Fewer than n nodes are output.
Which nodes start the queue?
Show answer
Those with indegree 0.
Takeaway Queue the zero-indegree nodes, remove edges as you pop; leftover nodes mean a cycle.
Dijkstra's shortest paths#
Single-source shortest paths with non-negative weights.
import heapq def dijkstra(n, adj, src): # adj[u] = [(v, w), ...], w >= 0 dist = [float('inf')] * n dist[src] = 0 pq = [(0, src)] while pq: d, u = heapq.heappop(pq) if d > dist[u]: continue # stale entry for v, w in adj[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(pq, (dist[v], v)) return dist
static long[] dijkstra(int n, List<List<int[]>> adj, int src) { // int[]{v, w} long[] dist = new long[n]; Arrays.fill(dist, Long.MAX_VALUE); dist[src] = 0; PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(x -> x[0])); pq.offer(new long[]{0, src}); while (!pq.isEmpty()) { long[] top = pq.poll(); int u = (int) top[1]; if (top[0] > dist[u]) continue; // stale entry for (int[] e : adj.get(u)) { long nd = top[0] + e[1]; if (nd < dist[e[0]]) { dist[e[0]] = nd; pq.offer(new long[]{nd, e[0]}); } } } return dist; }
Check yourself 2 questions
Dijkstra's weight requirement?
Show answer
Non-negative edge weights.
What do you do with stale heap entries?
Show answer
Skip them when popped if the distance is outdated.
Takeaway A min-heap of (distance, node), skipping stale entries; requires non-negative weights.
Union-Find (disjoint set union)#
Connected components, cycle detection in undirected graphs, Kruskal's MST, grouping accounts.
class DSU: def __init__(self, n): self.p = list(range(n)) self.sz = [1] * n def find(self, x): while self.p[x] != x: self.p[x] = self.p[self.p[x]] # path halving x = self.p[x] return x def union(self, a, b): a, b = self.find(a), self.find(b) if a == b: return False # already connected if self.sz[a] < self.sz[b]: a, b = b, a self.p[b] = a self.sz[a] += self.sz[b] return True
final class DSU { private final int[] p, sz; DSU(int n) { p = new int[n]; sz = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; sz[i] = 1; } } int find(int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } // path halving return x; } boolean union(int a, int b) { a = find(a); b = find(b); if (a == b) return false; if (sz[a] < sz[b]) { int t = a; a = b; b = t; } p[b] = a; sz[a] += sz[b]; return true; } }
Check yourself 2 questions
Name two uses of DSU.
Show answer
Any two of: connected components, undirected cycle detection, Kruskal's MST, grouping accounts.
Two optimisations that make it fast?
Show answer
Path compression and union by size or rank.
Takeaway Find with path compression and union by size give near-constant operations.
Trie#
Prefix queries, autocomplete, word search over a grid with many words.
class Trie: def __init__(self): self.root = {} def insert(self, word): node = self.root for ch in word: node = node.setdefault(ch, {}) node['$'] = True # end-of-word marker def _walk(self, s): node = self.root for ch in s: if ch not in node: return None node = node[ch] return node def search(self, word): node = self._walk(word) return bool(node and '$' in node) def starts_with(self, prefix): return self._walk(prefix) is not None
final class Trie { private static final class Node { Node[] next = new Node[26]; boolean end; } private final Node root = new Node(); void insert(String w) { Node n = root; for (char c : w.toCharArray()) { if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node(); n = n.next[c - 'a']; } n.end = true; } private Node walk(String s) { Node n = root; for (char c : s.toCharArray()) { n = n.next[c - 'a']; if (n == null) return null; } return n; } boolean search(String w) { Node n = walk(w); return n != null && n.end; } boolean startsWith(String p) { return walk(p) != null; } }
Check yourself 2 questions
Grid word search with many words: why a trie?
Show answer
It prunes paths that aren't a prefix of any word.
startsWith complexity?
Show answer
O(prefix length).
Takeaway A dict-of-dicts trie supports insert, search and prefix queries; great for word search with many words.
Backtracking: combination sum#
Enumerate subsets, combinations, permutations; choose, recurse, undo, and prune early.
def combination_sum(cands, target): # each candidate can be reused cands.sort() res, path = [], [] def dfs(start, remain): if remain == 0: res.append(path[:]); return for i in range(start, len(cands)): if cands[i] > remain: break # sorted, so prune the rest path.append(cands[i]) dfs(i, remain - cands[i]) # i, not i + 1: reuse allowed path.pop() # undo dfs(0, target) return res
static List<List<Integer>> combinationSum(int[] cands, int target) { Arrays.sort(cands); List<List<Integer>> res = new ArrayList<>(); dfs(cands, 0, target, new ArrayList<>(), res); return res; } static void dfs(int[] c, int start, int remain, List<Integer> path, List<List<Integer>> res) { if (remain == 0) { res.add(new ArrayList<>(path)); return; } for (int i = start; i < c.length && c[i] <= remain; i++) { path.add(c[i]); dfs(c, i, remain - c[i], path, res); // i: reuse allowed path.remove(path.size() - 1); // undo } }
Check yourself 2 questions
Three steps of backtracking?
Show answer
Choose, recurse, undo.
Why sort candidates first?
Show answer
So you can break early once a candidate exceeds the remaining target.
Takeaway Choose, recurse, undo, and prune early; sort to break once candidates exceed the target.
DP: take or skip, and 0/1 knapsack#
House robber style choices; knapsack with each item used at most once (loop capacity backwards).
def rob(nums): take = skip = 0 for x in nums: take, skip = skip + x, max(take, skip) return max(take, skip) def knapsack(weights, values, cap): dp = [0] * (cap + 1) # dp[c] = best value with capacity c for w, v in zip(weights, values): for c in range(cap, w - 1, -1): # backwards: each item once dp[c] = max(dp[c], dp[c - w] + v) return dp[cap]
static int rob(int[] nums) { int take = 0, skip = 0; for (int x : nums) { int t = skip + x; skip = Math.max(take, skip); take = t; } return Math.max(take, skip); } static int knapsack(int[] w, int[] v, int cap) { int[] dp = new int[cap + 1]; for (int i = 0; i < w.length; i++) for (int c = cap; c >= w[i]; c--) // backwards: each item once dp[c] = Math.max(dp[c], dp[c - w[i]] + v[i]); return dp[cap]; }
Check yourself 2 questions
Why loop capacity backwards in 0/1 knapsack?
Show answer
So each item is used at most once.
House robber recurrence?
Show answer
take = skip + x; skip = max(take, skip).
Takeaway Take-or-skip recurrences; 0/1 knapsack loops capacity backwards so each item is used once.
DP on two strings: longest common subsequence#
LCS, edit distance, distinct subsequences, wildcard matching: state is (i, j).
def lcs(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n]
static int lcs(String a, String b) { int m = a.length(), n = b.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]); return dp[m][n]; }
Check yourself 2 questions
LCS transition when characters match?
Show answer
dp[i][j] = dp[i−1][j−1] + 1.
When they don't?
Show answer
max(dp[i−1][j], dp[i][j−1]).
Takeaway State (i, j): match → dp[i−1][j−1] + 1, else max of dropping one side.
Linked list: reverse and find the middle#
Building blocks for palindrome lists, reorder list, reverse in k-groups.
def reverse(head): prev = None while head: nxt = head.next head.next = prev prev, head = head, nxt return prev def middle(head): # second middle for even length slow = fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next return slow
static ListNode reverse(ListNode head) { ListNode prev = null; while (head != null) { ListNode nxt = head.next; head.next = prev; prev = head; head = nxt; } return prev; } static ListNode middle(ListNode head) { // second middle for even length ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; }
Check yourself 2 questions
Variables needed to reverse a list?
Show answer
prev, the current node, and next.
Palindrome list recipe?
Show answer
Find the middle, reverse the second half, compare.
Takeaway Reverse with prev/cur/next; find the middle with fast/slow; combine for palindromes and reordering.
Tree DFS: return a value, update a global#
Diameter, max path sum, balanced check: each call returns what the parent needs.
def diameter(root): best = 0 def height(node): nonlocal best if not node: return 0 l, r = height(node.left), height(node.right) best = max(best, l + r) # longest path through this node (edges) return 1 + max(l, r) height(root) return best
private int best = 0; int diameter(TreeNode root) { best = 0; height(root); return best; } private int height(TreeNode node) { if (node == null) return 0; int l = height(node.left), r = height(node.right); best = Math.max(best, l + r); // longest path through this node return 1 + Math.max(l, r); }
Check yourself 2 questions
Max path sum: what's returned upward?
Show answer
node value + max(0, left, right): one arm.
What updates the global?
Show answer
node value + max(0, left) + max(0, right).
Takeaway Each call returns what the parent needs while updating a global answer.
Difference array and 2D prefix sums#
Many range updates then one read (difference array); many rectangle-sum queries on a fixed grid (2D prefix).
def range_add(n, updates): # updates: (l, r, v), inclusive diff = [0] * (n + 1) for l, r, v in updates: diff[l] += v diff[r + 1] -= v out, run = [], 0 for i in range(n): run += diff[i] out.append(run) return out def prefix_2d(g): # P[i+1][j+1] = sum of g[0..i][0..j] m, n = len(g), len(g[0]) P = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m): for j in range(n): P[i+1][j+1] = g[i][j] + P[i][j+1] + P[i+1][j] - P[i][j] return P def rect_sum(P, r1, c1, r2, c2): # inclusive corners return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]
static int[] rangeAdd(int n, int[][] updates) { // {l, r, v}, inclusive int[] diff = new int[n + 1]; for (int[] u : updates) { diff[u[0]] += u[2]; diff[u[1] + 1] -= u[2]; } int[] out = new int[n]; int run = 0; for (int i = 0; i < n; i++) { run += diff[i]; out[i] = run; } return out; } static long[][] prefix2d(int[][] g) { int m = g.length, n = g[0].length; long[][] P = new long[m + 1][n + 1]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) P[i+1][j+1] = g[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]; return P; } static long rectSum(long[][] P, int r1, int c1, int r2, int c2) { return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]; }
Check yourself 2 questions
Range add [l, r] by v with a difference array?
Show answer
diff[l] += v; diff[r + 1] −= v, then prefix-sum at the end.
2D rectangle sum formula idea?
Show answer
Inclusion–exclusion on the 2D prefix grid.
Takeaway Difference arrays make many range updates O(1) each; 2D prefix sums answer rectangle sums in O(1).
06Core patterns (Striver A2Z tables)
Coding/striver-a2z/MASTER_CHEATSHEET.md
Arrays & hashing#
| Pattern | Key insight |
|---|---|
| Dutch national flag | 3 pointers low/mid/hi; swap mid↔hi without mid++ |
| Boyer-Moore majority | cand/count; n/3 → 2 candidates + verify pass |
| Kadane | cur=max(x,cur+x); reset when cur<0 |
| Next permutation | find dip from right, swap with next larger, reverse suffix |
| Count inversions / reverse pairs | merge-sort counting during merge |
| Longest subarray sum k | prefix map seed {0:-1}, store first index only |
| Count subarrays sum k | seed {0:1}, add cnt[pre-k] |
| Subarrays XOR k | same as sum with XOR, seed {0:1} |
| Longest consecutive | set; only start from x where x-1 ∉ set |
Check yourself 2 questions
Dutch national flag pointers?
Show answer
low, mid and high; swap mid with high without advancing mid.
Majority element in O(1) space?
Show answer
Boyer-Moore voting.
Takeaway Dutch flag, Boyer-Moore majority and Kadane are the core array tricks.
Binary search shapes#
| Shape | Template |
|---|---|
| lower_bound | first idx a[i] ≥ x |
| upper_bound | first idx a[i] > x |
| rotated sorted | one half always sorted; check which |
| min of max (ship packages, split array, painters) | lo=max(a), hi=sum(a); feasible(mid) greedy |
| max of min (aggressive cows) | lo=1, hi=range; place greedily |
| Koko / min days bouquets | search speed/day; ceil division |
| Gas stations | search on real; iterate 100× or by count |
| Median of 2 sorted | partition smaller array; L1≤R2 & L2≤R1 |
| Kth missing | a[i]-(i+1) missing before i |
Check yourself 2 questions
upper_bound returns?
Show answer
The first index with a[i] > x.
Ship packages search range?
Show answer
lo = max(a), hi = sum(a).
Takeaway lower_bound, upper_bound, rotated arrays and min-of-max answers cover most binary searches.
Sliding window shapes#
| Shape | Rule |
|---|---|
| Fixed size k | add right, drop left at i-k |
| Longest valid (variable) | expand r; while invalid shrink l |
| Exactly K distinct | atMost(K) − atMost(K−1) |
| Char replacement | valid while len − maxFreq ≤ k (maxFreq never decreases) |
| Min window substring | need-count + formed; shrink while formed |
| Count subarrays w/ condition | add r-l+1 each step |
| Negatives present | window breaks → prefix sums / deque |
Check yourself 2 questions
Character replacement validity rule?
Show answer
Window length − max frequency ≤ k.
Fixed window of size k: when do you drop?
Show answer
Drop index i − k as you add i.
Takeaway Fixed size, longest valid, exactly K distinct and character replacement each have a rule.
Monotonic stack / deque#
| Problem | Stack keeps |
|---|---|
| Next greater element | decreasing; pop smaller, answer = top |
| Previous smaller | increasing |
| Largest rectangle histogram | increasing; on pop area = h×(i−left−1) |
| Maximal rectangle | histogram per row |
| Sum of subarray minimums | PSE & NSE; contrib = a[i]·left·right (strict on one side) |
| Stock span | decreasing with counts |
| Asteroid collision | stack of right-movers |
| Remove K digits | increasing; pop while top>d and k |
| Sliding window max | deque of indices, decreasing |
Check yourself 2 questions
Largest rectangle in a histogram: area on pop?
Show answer
h × (i − left − 1).
Previous smaller: stack order?
Show answer
Increasing.
Takeaway Next greater, previous smaller, histogram and maximal rectangle all use monotonic stacks.
Linked lists#
- Dummy head for anything that may change head
- Fast/slow: middle, cycle (Floyd), cycle start = reset one to head, step both
- Reverse in place: prev/cur/next; k-group = reverse segments + reconnect
- Intersection: switch heads at end (a+b = b+a)
- Copy random list: interleave clones, then split (O(1) space)
- LRU: hashmap + doubly linked list with dummy head/tail
- Add two numbers: carry; sort list: merge sort (find mid, split)
Check yourself 2 questions
How do you find a cycle's start?
Show answer
After fast and slow meet, reset one to head and step both by one.
Reverse in k-groups?
Show answer
Reverse each segment and reconnect.
Takeaway Dummy heads, Floyd's cycle detection and reversal in place cover most list problems.
Heaps & greedy#
| Problem | Insight |
|---|---|
| Kth largest | min-heap size k |
| Merge K sorted | heap of (val, list, idx) |
| Median of stream | max-heap low + min-heap high; balance sizes |
| Task scheduler | max(n_tasks, (f−1)(n+1)+#maxf) |
| Top K frequent | counter + heap or bucket sort O(n) |
| Meeting rooms II | sort starts, min-heap of end times |
| Jump game | track farthest reach |
| Gas station | if total≥0 answer = start after last negative |
| Activity selection / non-overlap | sort by end time |
| Candy | two passes left→right, right→left |
Check yourself 2 questions
Task scheduler formula?
Show answer
max(n_tasks, (f − 1)(n + 1) + count of max-frequency tasks).
Merge K sorted lists: heap entries?
Show answer
(value, list index, element index).
Takeaway Kth largest, merging k lists, stream medians and task scheduling are heap or greedy classics.
Matrix and grid techniques#
| Task | Technique | Complexity | Watch out |
|---|---|---|---|
| Spiral order | Keep four boundaries (top, bottom, left, right); walk one edge, then shrink that boundary | O(mn) | Check top ≤ bottom and left ≤ right again before the third and fourth edges |
| Rotate 90° clockwise in place | Transpose, then reverse each row (anticlockwise: transpose, then reverse each column) | O(n²), O(1) | Only square matrices rotate in place |
| Set matrix zeroes | Use the first row and column as marker arrays, with two flags for themselves | O(mn), O(1) | Process the first row and column last |
| Search a sorted matrix | Fully sorted: treat as 1D (i / n, i % n). Rows and columns sorted: staircase from the top-right | O(log mn) / O(m + n) | Pick the right variant by reading how it's sorted |
| Diagonals | Cells on one diagonal share i − j; anti-diagonals share i + j | O(mn) | Use i − j + (n − 1) as a non-negative key |
| Submatrix sums | 2D prefix sums (template below) | O(mn) build, O(1) query | Pad with a zero row and column to avoid bounds checks |
| Islands, flood fill, regions | BFS or DFS over 4 (or 8) neighbours; mark visited on entry | O(mn) | Deep recursion on 10⁶ cells: prefer an explicit stack or BFS |
| Shortest path in a grid | BFS (unit cost), 0-1 BFS (0/1 cost), Dijkstra (weighted); multi-source BFS for "distance to nearest X" | O(mn) to O(mn log mn) | Encode state as (r, c[, extra]) when keys or obstacles matter |
| Paths counting / min path | Grid DP from top-left; one rolling row is enough | O(mn), O(n) | Obstacles set dp to 0; initialise the first row and column carefully |
| Largest rectangle of 1s | Build a histogram per row, then largest rectangle with a monotonic stack | O(mn) | Reset heights to 0 on a 0 cell |
Check yourself 2 questions
Rotate a matrix 90° clockwise in place?
Show answer
Transpose, then reverse each row.
Spiral order pitfall?
Show answer
Re-check top ≤ bottom and left ≤ right before the return legs.
Takeaway Spiral with four shrinking boundaries, rotate by transpose plus reverse, and grid BFS or DFS.
07Trees, graphs, tries, strings, bits
Coding/striver-a2z/MASTER_CHEATSHEET.md (Parts on trees, graphs, tries, strings, bits, ‘Beyond the sheet’)
Binary trees & BST#
| Problem | Insight |
|---|---|
| Diameter | height fn returns 1 arm; global = l+r |
| Max path sum | return val+max(0,l,r); global uses both arms |
| LCA (BT) | if root in {p,q} return root; both sides non-null → root |
| LCA (BST) | walk: both smaller → left, both larger → right |
| Validate BST | pass (lo,hi) bounds |
| Kth smallest BST | inorder iterative, count |
| Views (top/bottom/left/right) | BFS with column / level map |
| Serialize | preorder with null markers |
| Build from pre+in | map inorder idx; recurse ranges |
| Burn tree / nodes at dist K | parent map + BFS |
| Morris traversal | thread to predecessor, O(1) space |
| Balanced check | height returns −1 as soon as a subtree is unbalanced |
| Path sum III (any start) | prefix sums along the root path in a hashmap; undo on return |
| Inorder successor (BST) | right child → its leftmost; else the last ancestor where you went left |
| Recover swapped BST nodes | inorder walk; the two inversions name the swapped pair |
Check yourself 2 questions
LCA in a binary tree?
Show answer
If root is p or q return it; if both sides are non-null, root is the LCA.
LCA in a BST?
Show answer
Walk down: both smaller go left, both larger go right, otherwise current node.
Takeaway Diameter, max path sum and LCA follow the return-one-arm, combine-both pattern.
Graphs#
| Algo | When / key rule |
|---|---|
| BFS | unweighted shortest path; multi-source (rotten oranges) |
| DFS | components, cycle (undirected: parent; directed: path-visited) |
| Topo (Kahn) | indegree 0 queue; size≠n → cycle |
| Dijkstra | PQ of (d,node); skip stale entries; non-negative only |
| Bellman-Ford | relax V−1 times; Vth relax → negative cycle |
| Floyd-Warshall | k outermost; dist[i][i]<0 → neg cycle |
| Prim / Kruskal | MST; Kruskal = sort edges + DSU |
| DSU | path compression + union by rank/size ≈ O(α) |
| Tarjan bridges | bridge if low[v] > tin[u] |
| Articulation | low[v] ≥ tin[u] (root: ≥2 children) |
| Kosaraju SCC | order by finish, reverse graph, DFS |
| 0-1 BFS | deque: weight 0 → front, 1 → back |
Check yourself 2 questions
Undirected versus directed cycle detection with DFS?
Show answer
Undirected: track the parent; directed: track the current path.
Rotten oranges uses which BFS variant?
Show answer
Multi-source BFS.
Takeaway BFS for unweighted paths, DFS for components and cycles, Kahn for topological order, Dijkstra for weights.
Tries, strings, bits, maths#
| Topic | Key |
|---|---|
| Trie | children[26] + end flag; count prefix |
| Max XOR pair | bit trie, greedily take opposite bit |
| KMP | LPS array; O(n+m) |
| Z-function | z[i] = longest prefix match starting at i; search on P$T |
| Rabin-Karp | rolling hash; verify on hit |
| Longest palindrome | expand around centre (2n−1 centres) / Manacher |
| XOR 1..n | [n,1,n+1,0][n%4] |
| Lowest set bit | x&-x; clear: x&(x-1) |
| Submask enumeration | s=(s-1)&mask |
| Sieve | mark from p², O(n log log n); SPF sieve for factorisation |
| Fast power | binary exponentiation mod M |
Check yourself 2 questions
KMP complexity?
Show answer
O(n + m).
What does z[i] store?
Show answer
The longest prefix match starting at i.
Takeaway Tries with counts, bit tries for XOR, KMP's LPS array, the Z-function and core maths.
Beyond the sheet — triggers#
| Trigger | Tool |
|---|---|
| range sum + point update | Fenwick (BIT) |
| range update + range query | lazy segment tree |
| static range min, many queries | sparse table O(1) |
| count numbers in [L,R] with digit property | digit DP |
| answer for every root | rerooting DP |
| k-th ancestor / LCA many queries | binary lifting |
| n≈40 subset sums | meet-in-the-middle |
| random sample from stream | reservoir sampling |
Check yourself 2 questions
Range sum with point updates?
Show answer
Fenwick tree (BIT).
Count numbers in [L, R] with a digit property?
Show answer
Digit DP.
Takeaway Range sum with point updates → Fenwick; range updates and queries → lazy segment tree; digit property counts → digit DP.
Graph picker#
flowchart TD
A[Graph problem] --> B{{Edge weights?}}
B -->|none| C[BFS]
B -->|0 or 1| D[0-1 BFS]
B -->|non-negative| E[Dijkstra]
B -->|negative| F[Bellman-Ford]
A --> G{{All pairs, n small?}}
G -->|yes| H[Floyd-Warshall]
A --> I{{Ordering or deps?}}
I -->|yes| J[Topo sort]
A --> K{{Connect cheapest?}}
K -->|yes| L[Kruskal + DSU]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class B,G,I,K decCheck yourself 2 questions
Edge weights 0 or 1?
Show answer
0-1 BFS with a deque.
Negative weights?
Show answer
Bellman-Ford.
Takeaway No weights → BFS; 0/1 → 0-1 BFS; non-negative → Dijkstra; negative → Bellman-Ford; all pairs small n → Floyd.
Randomised algorithms#
| Technique | How | Use for |
|---|---|---|
| Reservoir sampling | Keep the first k; for item i (1-based) replace a random slot with probability k / i | Uniform sample from a stream of unknown length; random node of a linked list |
| Fisher–Yates shuffle | For i from n − 1 down to 1, swap a[i] with a[rand(0..i)] | Unbiased in-place shuffle in O(n) |
| Random pick with weight | Prefix sums of weights, draw r in [1, total], binary search the first prefix ≥ r | Weighted sampling, load balancing by capacity |
| Randomised quickselect | Random pivot, recurse into one side | Kth element in expected O(n) |
| Rejection sampling | Generate a larger uniform range, discard values outside the target range | rand10 from rand7 (use 7·(a−1)+b, reject > 40) |
| Random hashing | Random base or modulus for rolling hashes | Make adversarial collisions unlikely |
| Skip list | Each node promoted to the next level with probability ½ | Ordered set with expected O(log n) ops (Redis sorted sets) |
Check yourself 2 questions
Reservoir sampling: when does item i replace a slot?
Show answer
With probability k / i.
Expected complexity of quickselect?
Show answer
O(n).
Takeaway Reservoir sampling, randomised quickselect and shuffles give uniform choices and expected-time guarantees.
Maths toolkit: modular arithmetic, combinatorics, geometry#
def mod_pow(b, e, m): # O(log e) r = 1; b %= m while e: if e & 1: r = r * b % m b = b * b % m; e >>= 1 return r MOD = 10**9 + 7 def ncr_table(n): # O(n) precompute, O(1) per query f = [1] * (n + 1) for i in range(1, n + 1): f[i] = f[i-1] * i % MOD inv = [1] * (n + 1); inv[n] = mod_pow(f[n], MOD - 2, MOD) for i in range(n, 0, -1): inv[i-1] = inv[i] * i % MOD return lambda a, b: 0 if b < 0 or b > a else f[a] * inv[b] % MOD * inv[a-b] % MOD
- Geometry habits: compare squared distances to avoid square roots; use integer cross products, not slopes; convex hull with the monotone chain in O(n log n).
- Manhattan tricks: rotate 45° with (x + y, x − y) to turn Manhattan distance into Chebyshev.
- Counting: inclusion–exclusion for "divisible by a or b"; pigeonhole for guaranteed duplicates.
Check yourself 2 questions
Modular inverse of b mod prime p?
Show answer
b^(p−2) mod p.
nCr mod p with precomputation?
Show answer
fact[n] · inv[r] · inv[n − r].
Takeaway Reduce mod after every operation, invert with Fermat for prime moduli, precompute factorials for nCr.
08Graph algorithms — templates
practice/graph.md, dsu.md, practice/algorithms/06,07,15_*.py, striver-a2z/27-graphs (25-dijkstra, 44-kosaraju, 45-bridges)
Which graph algorithm?#
flowchart LR
S["Graph problem"] --> Q{{"What is asked?"}}
Q -->|"reachability / components / flood"| T["BFS or DFS<br/>(DSU if edges arrive online)"]
Q -->|"cycle?"| C{{"Directed?"}}
C -->|"no"| CU["DFS/BFS with parent<br/>or DSU"]
C -->|"yes"| CD["DFS with path set<br/>or Kahn: processed < V"]
Q -->|"order with dependencies"| TS["Topological sort<br/>(Kahn / DFS finish order)"]
Q -->|"shortest path"| W{{"Edge weights?"}}
W -->|"all equal"| B["BFS (multi-source if many starts)"]
W -->|"0 / 1"| Z["0-1 BFS with deque"]
W -->|"DAG, any sign"| D["relax in topological order"]
W -->|"non-negative"| DJ["Dijkstra (min-heap)"]
W -->|"negative, single source"| BF["Bellman-Ford (V−1 rounds)"]
W -->|"all pairs, V ≤ ~400"| FW["Floyd-Warshall"]
Q -->|"connect everything cheaply"| M["MST: Kruskal (DSU) / Prim (heap)"]
Q -->|"critical edges / nodes / SCC"| L["Tarjan low-link / Kosaraju"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,C,W decCheck yourself 2 questions
Undirected cycle detection with edges arriving online?
Show answer
DSU: an edge joining two nodes already connected makes a cycle.
Minimum spanning tree algorithms?
Show answer
Kruskal (with DSU) or Prim (with a heap).
Takeaway Reachability → BFS/DFS (DSU online); cycles → DSU or colours; ordering → topo sort; paths → BFS, Dijkstra or Bellman-Ford; MST → Kruskal or Prim.
Goal → algorithm#
| Goal | Algorithm | Key detail |
|---|---|---|
| Shortest path, unweighted | BFS | mark visited on enqueue not dequeue |
| Shortest path, weighted (≥0) | Dijkstra | if d > dist[u]: continue for stale entries |
| Shortest path, negative weights | Bellman-Ford | copy dist each round, N−1 iterations |
| Connectivity / components | DFS + outer loop | count how many times outer loop fires |
| Ordering with dependencies | Topo sort (Kahn) | len(order) != n → cycle |
| Cycle in directed graph | 3-state DFS (0/1/2) | state 1 = on current stack |
| Cycle in undirected graph | DFS + parent / DSU | nei != parent |
| Bipartite | BFS, flip colours | contradiction = not bipartite |
| Closest source distance | Multi-source BFS | seed all sources at distance 0 |
| Can X reach Y cheaply | Reverse BFS/DFS from Y | Pacific Atlantic |
| All pairs, V ≤ ~400 | Floyd-Warshall | k outermost |
| Connect everything cheaply | Kruskal (DSU) / Prim (heap) | |
| Critical edges / SCC | Tarjan low-link / Kosaraju | low[v] > tin[u] ⇒ bridge |
Check yourself 2 questions
When should BFS mark nodes visited?
Show answer
On enqueue, not dequeue.
Dijkstra stale-entry check?
Show answer
if d > dist[u]: continue.
Takeaway Unweighted → BFS marked on enqueue; non-negative weights → Dijkstra skipping stale; negative → Bellman-Ford.
BFS (mark on enqueue) O(V+E)#
visited = {start}; q = deque([start]) while q: node = q.popleft() for nei in graph[node]: if nei not in visited: visited.add(nei); q.append(nei)
Check yourself 2 questions
What goes wrong if you mark on dequeue?
Show answer
Duplicates in the queue and wrong distances.
Which container does BFS use?
Show answer
A deque (FIFO queue).
Takeaway Add to visited when enqueuing so no node enters the queue twice.
DFS components (outer loop mandatory) O(V+E)#
for i in range(n): if i not in visited: visited.add(i); dfs(i); count += 1
Check yourself 2 questions
Why is the outer loop mandatory?
Show answer
Graphs can be disconnected; one DFS misses other components.
How do you count components?
Show answer
Count the DFS starts from unvisited nodes.
Takeaway Loop over every node and start a DFS from each unvisited one; each start is a component.
Cycle, directed: 3-state DFS O(V+E)#
state = [0]*n # 0 new, 1 on stack, 2 done def dfs(u): state[u] = 1 for v in g[u]: if state[v] == 1: return True if state[v] == 0 and dfs(v): return True state[u] = 2; return False
Check yourself 2 questions
What do the three states mean?
Show answer
0 new, 1 on the current path (stack), 2 done.
Why not use parent tracking for directed graphs?
Show answer
Directed cycles need on-path tracking, not a parent check.
Takeaway States new, on stack, done: reaching an on-stack node means a cycle.
Topo sort — Kahn O(V+E)#
q = deque(i for i in range(n) if indeg[i] == 0) while q: u = q.popleft(); order.append(u) for v in g[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) return order if len(order) == n else [] # [] = cycle
Check yourself 2 questions
What does len(order) < n mean?
Show answer
The graph has a cycle.
When is a neighbour enqueued?
Show answer
When its indegree drops to 0.
Takeaway Queue zero-indegree nodes, decrement neighbours, and an order shorter than n means a cycle.
Dijkstra O((V+E) log V)#
dist = [INF]*V; dist[src] = 0; pq = [(0, src)] while pq: du, u = heapq.heappop(pq) if du > dist[u]: continue # stale for v, w in adj[u]: if du + w < dist[v]: dist[v] = du + w heapq.heappush(pq, (dist[v], v))
Check yourself 2 questions
Why skip when du > dist[u]?
Show answer
The entry is stale; a shorter path was already processed.
Complexity with a heap?
Show answer
O((V + E) log V).
Takeaway Pop the smallest distance, skip stale entries, relax edges and push improvements.
Bellman-Ford (K stops) O(V·E)#
dist = [INF]*n; dist[src] = 0 for _ in range(k + 1): # n-1 rounds for plain BF new = dist[:] # COPY each round for u, v, w in edges: if dist[u] != INF and dist[u] + w < new[v]: new[v] = dist[u] + w dist = new # one more relaxation succeeds ⇒ negative cycle
Check yourself 2 questions
Why copy the distance array each round?
Show answer
So one round can't chain several edges, which would break the stop limit.
How many rounds for plain Bellman-Ford?
Show answer
n − 1.
Takeaway Relax all edges in rounds; for K stops run K + 1 rounds and copy the distance array each round.
Floyd-Warshall O(V³), O(V²)#
for k in range(n): for i in range(n): if dist[i][k] == INF: continue for j in range(n): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j]
Check yourself 2 questions
Which loop must be outermost?
Show answer
k, the intermediate node.
Complexity?
Show answer
O(n³).
Takeaway Triple loop with k outermost gives all-pairs shortest paths in O(n³).
Prim MST O(E log V)#
heap = [(0, 0)]; total = used = 0 while heap and used < n: w, u = heapq.heappop(heap) if visited[u]: continue visited[u] = True; total += w; used += 1 for wt, v in graph[u]: if not visited[v]: heapq.heappush(heap, (wt, v)) return total if used == n else -1
Check yourself 2 questions
What does Prim's heap hold?
Show answer
(weight, node) edges leaving the tree.
When do you skip a popped node?
Show answer
If it's already visited.
Takeaway Grow the tree from a start node with a min-heap of edges, skipping visited nodes.
DSU + Kruskal ≈O(α(n)) per op; Kruskal O(E log E)#
parent = list(range(n)); rank = [0]*n # NOT [0]*n def find(x): while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x] return x def union(a, b): a, b = find(a), find(b) if a == b: return False # already connected if rank[a] < rank[b]: a, b = b, a parent[b] = a if rank[a] == rank[b]: rank[a] += 1 return True # Kruskal: for w,u,v in sorted(edges): if union(u,v): total += w
Check yourself 2 questions
Kruskal's order of edges?
Show answer
Ascending weight.
When is an edge skipped?
Show answer
When both ends are already in the same set.
Takeaway Sort edges by weight and union endpoints in different sets; path compression and rank keep it fast.
Tarjan bridges (low-link) O(V+E)#
def dfs(u, p): nonlocal timer tin[u] = low[u] = timer; timer += 1 for v in adj[u]: if v == p: continue if tin[v] != -1: # back edge low[u] = min(low[u], tin[v]); continue dfs(v, u) low[u] = min(low[u], low[v]) if low[v] > tin[u]: out.append([u, v]) # bridge
Check yourself 2 questions
Bridge condition?
Show answer
low[v] > tin[u].
What does low[u] store?
Show answer
The earliest discovery time reachable from u's subtree via one back edge.
Takeaway Track discovery time and low-link; an edge u–v is a bridge if low[v] > tin[u].
Kosaraju SCC O(V+E)#
# 1) DFS on adj, push u on FINISH → order # 2) DFS on reversed graph in reversed(order) for u in reversed(order): if not vis[u]: count += 1; dfs2(u) # each call = one SCC
Check yourself 2 questions
Kosaraju's two passes?
Show answer
DFS for finish order, then DFS on the reversed graph in reverse finish order.
What does each second-pass DFS find?
Show answer
One strongly connected component.
Takeaway DFS to record finish order, then DFS on the reversed graph in reverse finish order; each call is an SCC.
0-1 BFS / multi-source O(V+E)#
dq = deque([src]); dist[src] = 0 while dq: u = dq.popleft() for v, w in adj[u]: if dist[u] + w < dist[v]: dist[v] = dist[u] + w dq.appendleft(v) if w == 0 else dq.append(v) # multi-source: seed ALL sources at distance 0
Check yourself 2 questions
Where do 0-weight neighbours go?
Show answer
The front of the deque (appendleft).
How do you seed multi-source BFS?
Show answer
Put every source in the queue at distance 0.
Takeaway With 0/1 weights, push 0-edges to the front and 1-edges to the back of a deque.
Common mistakes#
- Forgetting disconnected graphs — always outer-loop over all nodes
- Marking visited on dequeue instead of enqueue → duplicates, wrong distances
- Parent-tracking DFS on a directed graph — use 3-state DFS instead
- Dijkstra without
if d > dist[u]: continue - Topo sort without the
len(order) == ncheck - Bellman-Ford updating dist in place — copy before each round
- DSU:
parent = [0]*n; forgettingreturn Falsewhen a == b - DFS for shortest paths in an unweighted graph: use BFS
- Dijkstra with negative edges: use Bellman-Ford
- Recursive DFS on 105 nodes in Python hits the recursion limit: go iterative
- Undirected graph built with only one direction of each edge
- Union-find without path compression and union by rank degrades to O(n) per operation
Check yourself 2 questions
Parent-tracking DFS on a directed graph: problem?
Show answer
It misses directed cycles; use 3-state colouring.
Name another common graph mistake.
Show answer
Any of: no outer loop for disconnected graphs, marking visited on dequeue, missing path compression.
Takeaway Forgetting disconnected graphs, marking on dequeue, parent tracking on directed graphs, and DSU without path compression.
Problems to know cold#
| Problem | LC | Pattern |
|---|---|---|
| Number of Islands | 200 | Grid DFS |
| Clone Graph | 133 | DFS + hashmap |
| Pacific Atlantic | 417 | Reverse DFS from borders |
| Course Schedule I/II | 207/210 | Topo sort (Kahn) |
| Word Ladder | 127 | BFS + string transform |
| Rotting Oranges | 994 | Multi-source BFS |
| Network Delay Time | 743 | Dijkstra |
| Cheapest Flights K Stops | 787 | Bellman-Ford |
| Redundant Connection | 684 | DSU / cycle |
| Is Graph Bipartite | 785 | BFS 2-colouring |
| Alien Dictionary | 269 | Topo sort on characters |
| Accounts Merge | 721 | DSU + sorting |
Check yourself 2 questions
Course Schedule I/II pattern?
Show answer
Topological sort (Kahn).
Pacific Atlantic trick?
Show answer
Reverse DFS from the borders.
Takeaway Islands, clone graph, Pacific Atlantic, course schedule and word ladder are the graph classics.
All 46 striver graph problems with best approach
- Traversal Techniques — BFS + iterative DFS: explicit stack, push neighbours reversed, mark on pop O(V + E)
- Connected Components — Adjacency list + BFS: build lists; BFS from each unvisited node O(V + E)
- Number of provinces — DFS on the matrix: for each unvisited city, DFS scanning its row O(n²)
- Number of islands — BFS flood: queue per island, mark when pushed O(m·n)
- Flood fill algorithm — Recursive DFS: repaint, recurse on same-colour neighbours O(m·n)
- Number of enclaves — Multi-source BFS from the border: flood from border land; count the rest O(m·n)
- Rotten Oranges — Multi-source BFS: queue all rotten at t = 0; process level by level O(m·n)
- Distance of nearest cell having one — Multi-source BFS: seed all 1s with distance 0 O(m·n)
- Surrounded Regions — Mark from the border: border O → '#', flood; then O→X, #→O O(m·n)
- Number of distinct islands — Relative coordinates: store (r − r0, c − c0) of every cell in DFS order O(m·n)
- Detect a cycle in an undirected graph — DFS with parent: dfs(u, p): visited neighbour ≠ p ⇒ cycle O(V + E)
- Bipartite graph — BFS colouring: queue; neighbour gets the opposite colour O(V + E)
- Topological sort or Kahn's algorithm — Kahn's algorithm (BFS on in-degrees): queue of in-degree-0 nodes; decrement neighbours O(V + E)
- Detect a cycle in a directed graph — Kahn's algorithm: cycle iff fewer than V nodes get processed O(V + E)
- Find eventual safe states — Kahn on the reversed graph: reverse edges, peel out-degree-0 nodes O(V + E)
- Course Schedule I — Kahn's algorithm: process in-degree 0 courses; all n processed? O(V + E)
- Course Schedule II — Kahn's algorithm: pop in-degree-0 courses in order O(V + E)
- Alien dictionary — Adjacent pairs + Kahn: first mismatch of neighbours → edge; Kahn on k letters O(N·L + k)
- Shortest path in DAG — Topological order + relaxation: Kahn order; relax out-edges once O(V + E)
- Shortest path in undirected graph with unit weights — BFS: dist set at discovery is final O(V + E)
- Word ladder I — BFS with on-the-fly neighbours: try 26 letters per position; remove from set when queued O(N·L²·26)
- Word ladder II — BFS depth map + backtracking: depth per word, then DFS back from end O(N·L²·26 + paths·len)
- Dijkstra's algorithm — Min-heap with lazy deletion: pop smallest (d, u); skip stale; relax O((V + E) log V)
- Print shortest path — Dijkstra with parent pointers: parent[v] = u on every improvement; walk back from n O((n + m) log n)
- Shortest distance in a binary maze — BFS: distance grid; first discovery is final O(nm)
- Path with minimum effort — Dijkstra on max-step: heap of (effort, r, c); relax with max O(nm log nm)
- Cheapest flights within K stops — Bellman-Ford with k + 1 rounds: relax every edge from the previous round's snapshot O(k·E)
- Minimum multiplications to reach end — BFS over residues: dist array, −1 = unseen; return at discovery of end | O(10⁵· | arr )
- Number of ways to arrive at destination — Dijkstra with ways array: improve → ways[v] = ways[u]; tie → ways[v] += ways[u] O(E log V)
- Bellman-Ford algorithm — Bellman-Ford (V − 1 rounds + check): relax all edges V−1 times; one more improving pass ⇒ negative cycle O(V·E)
- Floyd Warshall algorithm — Floyd-Warshall triple loop: for k: for i: for j: d[i][j] = min(d[i][j], d[i][k] + d[k][j]) O(n³)
- Find the city with the smallest number of neighbors at a threshold distance — Floyd-Warshall + count: all-pairs matrix, then count per row O(n³)
- Network delay time — Dijkstra: heap from k; answer = max dist O(E log n)
- Swim in rising water — Min-heap flood (Dijkstra): always expand the lowest reachable cell; track the max so far O(n² log n)
- Disjoint Set (Union-Find) — Union by size + path compression: smaller root under larger; find flattens the path O(α(n)) amortised
- Find the MST weight — Kruskal's algorithm: sort edges by weight; accept an edge if DSU says its ends differ O(E log E)
- Number of operations to make network connected — DSU: union every cable; components = n − successful unions O(n + E·α(n))
- Accounts merge — DSU on account indices: email → first owner; union owners; group emails by root O(N log N)
- Number of islands II — Online DSU: new cell +1; each union with a distinct neighbour −1 O(n·m + k·α)
- Making a large island — DSU sizes + distinct neighbour roots: union all land; each 0 scores 1 + Σ distinct neighbour sizes O(n²·α)
- Most stones removed with same row or column — DSU on row and column nodes: union(row x, col y + OFFSET) per stone; count roots among used nodes O(n·α)
- Kosaraju's algorithm — Kosaraju (two DFS passes): DFS for finish order; DFS on reversed graph in reverse finish order O(V + E)
- Bridges in graph — Tarjan tin / low: DFS; low[u] = min(tin[u], low[child], tin[back-edge target]); bridge if low[v] > tin[u] O(V + E)
- Articulation point in graph — Tarjan tin / low: non-root: low[child] ≥ tin[u]; root: ≥ 2 children O(V + E)
09Dynamic programming — every family in depth
practice/dp.md, DP-patterns/*/README.md, striver-a2z/28-dynamic-programming (54 problems)
The framework — 4 questions#
- State — what does
dp[i]mean, as an exact English sentence? - Recurrence — how does dp[i] depend on smaller states? write the maths first
- Base cases — derive from the definition (dp[0] = 1 = “one way to do nothing”)
- Answer location — dp[n], max(dp), dp[0][n−1]…
flowchart LR
S["Optimise / count over choices"] --> Q{{"What does the state index?"}}
Q -->|"position in one array"| D1["1D DP<br/>dp[i] from dp[i−1], dp[i−2]…"]
Q -->|"cell in a grid"| GR["Grid DP<br/>dp[i][j] from up / left / diag"]
Q -->|"(index, remaining capacity / target)"| KS{{"Item reusable?"}}
KS -->|"no"| K01["0/1 knapsack<br/>pick → i−1"]
KS -->|"yes"| KU["Unbounded<br/>pick → stay at i"]
Q -->|"(day, holding?, transactions)"| ST["Stock state machine"]
Q -->|"(index, previous chosen index)"| LIS["LIS family<br/>O(n²) or patience O(n log n)"]
Q -->|"(i in s, j in t)"| STR["Two-string DP<br/>LCS / edit distance / matching"]
Q -->|"interval (i, j) with a split k"| MCM["Partition DP<br/>dp[i][j] = min over k"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,KS decCheck yourself 2 questions
First DP question?
Show answer
What does dp[i] mean, as an exact sentence?
How should base cases be chosen?
Show answer
Derived from the definition, not guessed.
Takeaway Define the state in a sentence, write the recurrence, derive base cases from the definition, then the fill order and answer.
Signal → pattern#
| Signal | Pattern |
|---|---|
| 1D array, choices affect neighbours | 1D linear |
| grid, move right/down | 2D grid |
| two strings, alignment / edit | two-sequence |
| take or leave with capacity | knapsack (0/1 backward, unbounded forward) |
| longest increasing / chain | LIS family |
| burst / cut / merge contiguous | interval (fill by length) |
| node needs children first | tree DP (postorder, return pair) |
| buy/sell with rules | stock state machine |
| n ≤ 20, subset state | bitmask DP |
| count integers ≤ N with property | digit DP (L4+) |
- Backward
range(target, x-1, -1)→ each item at most once - Forward
range(x, target+1)→ reusable unlimited - Coin change II (combinations): coins OUTER loop, amount inner
Check yourself 2 questions
Two strings with alignment or edits?
Show answer
Two-sequence DP.
Take or leave with a capacity?
Show answer
Knapsack (0/1 backward, unbounded forward).
Takeaway 1D neighbours → linear DP; grid moves → 2D DP; two strings → two-sequence; capacity → knapsack.
Every DP family: state · transition · base · fill order · answer#
| Family | State | Transition | Base | Fill order | Answer / optimise |
|---|---|---|---|---|---|
| 1D linear | dp[i] = best/ways up to i | Climb: dp[i]=dp[i−1]+dp[i−2]; Rob: max(dp[i−1], a[i]+dp[i−2]); Frog: min(dp[i−j]+|h|) | dp[0], dp[1] | i ↑ | dp[n−1]; keep prev2, prev1 → O(1) |
| 2D grid | dp[i][j] = paths/cost to (i,j) | dp[i][j] = g + min(up, left); paths = up + left | row 0 / col 0; blocked = 0 | row by row | dp[m−1][n−1]; 1D rolling row |
| Stock state machine | (day, holding, tx left) | buy = max(buy, −p) / sell = max(sell, buy+p); fee / cooldown variants | cash 0, hold −∞ | day ↑ | sell state |
| 0/1 knapsack / subset | dp[i][t] = can/ways/max with items ..i, capacity t | not-take dp[i−1][t]; take dp[i−1][t−w] | dp[0] = True / 1 | t DESCENDING (1D) | dp[target] |
| Unbounded knapsack | dp[t] with reusable items | take → stay at i: dp[t−w] same row | dp[0] = 0 (min) / 1 (ways) | t ASCENDING | dp[amount] |
| LIS family | dp[i] = longest ending at i | dp[i] = 1 + max dp[j], j‹i, a[j]‹a[i]; or tails + lower_bound | dp[i] = 1 | i ↑, j ‹ i | max(dp); len(tails) (tails ≠ actual LIS) |
| Two strings (LCS/edit) | dp[i][j] = answer for s1[:i], s2[:j] | match → diag+1; else max(up,left) / 1+min(ins,del,rep) | row/col 0 = empty string | i ↑, j ↑ | dp[n][m]; s1[i−1] aligns with dp[i] |
| Interval / partition (MCM) | dp[i][j] = best for a[i..j] | min over k of dp[i][k] + dp[k+1][j] + cost | dp[i][i] = 0 | by LENGTH (i ↓, j ↑) | dp[0][n−1]; burst balloons: choose LAST |
| Tree DP | f(node) returns pair/states | rob = val + skipL + skipR; skip = max(L)+max(R) | null → (0,0) | postorder | max(f(root)) |
| Bitmask DP | dp[mask][last] | dp[mask|1‹‹v][v] = min(dp[mask][u] + w) | dp[1‹‹s][s] = 0 | masks ↑ | min over last of dp[full][last] |
Check yourself 2 questions
Climbing stairs transition?
Show answer
dp[i] = dp[i−1] + dp[i−2].
House robber transition?
Show answer
max(dp[i−1], a[i] + dp[i−2]).
Takeaway Every DP family has a state, transition, base, fill order and answer; the table lists them side by side.
1D linear — practice problems#
- Climbing stairs — Tabulation with two variables: iterate bottom-up keeping prev2, prev1 O(n)
- Frog Jump — Tabulation, O(1) space: keep dp[i−1], dp[i−2] only O(n)
- Frog jump with K distances — Tabulation: fill dp left to right O(n·k)
- Maximum sum of non adjacent elements — Space-optimised tabulation: prev = dp[i−1], prev2 = dp[i−2] O(n)
- House robber — Two passes by index range: same, without copying O(n)
- Ninja's training — Tabulation with one row: prev[t] = best ending with t yesterday O(n·9)
Check yourself 2 questions
Space-optimised climbing stairs?
Show answer
Keep only prev1 and prev2: O(1) space.
Frog jump with K distances complexity?
Show answer
O(n·k).
Takeaway Climbing stairs, frog jumps and house robber reduce to rolling two variables.
2D grid — practice problems#
- Grid unique paths — 1D rolling row: row[j] += row[j−1] O(m·n)
- Unique paths II — 1D rolling row: row[j] = 0 if blocked else row[j] + row[j−1] O(m·n)
- Minimum Falling Path Sum — Row-by-row tabulation: prev row → cur row O(n²)
- Triangle — Bottom-up with one row: dp = last row; move up O(n²)
- Cherry pickup II — Bottom-up with a 2D layer: front[c1][c2] from the row below O(R·C²·9)
- Count Square Submatrices with All Ones — DP on the bottom-right corner: dp = 1 + min(up, left, diag); sum dp O(m·n)
- Minimum path sum in a grid — 1D rolling DP: row[j] = g[i][j] + min(row[j], row[j-1]) O(mn)
Check yourself 2 questions
Unique paths with a rolling row?
Show answer
row[j] += row[j−1].
Obstacle handling?
Show answer
row[j] = 0 if blocked.
Takeaway Grid paths roll one row; blocked cells reset to zero.
Stock state machine — practice problems#
- Best time to buy and sell stock — Running minimum: profit = price − min so far O(n)
- Best time to buy and sell stock II — Tabulated state machine, O(1): aheadBuy, aheadSell rolled backward O(n)
- Best time to buy and sell stock III — Four forward variables: buy1, sell1, buy2, sell2 O(n)
- Best time to buy and sell stock IV — Forward buy[]/sell[] arrays: k copies of the Stock III chain O(n·k)
- Best time to buy and sell stock with transaction fees — Forward hold / cash: cash = max(cash, hold + p − fee) O(n)
- Best time to buy and sell stock with cooldown — Backward tabulation with two look-ahead rows: front1, front2 O(n)
Check yourself 2 questions
Single transaction best profit?
Show answer
price − running minimum, maximised.
What extends the state for cooldown or fees?
Show answer
An extra state or a fee term in the transitions.
Takeaway Stock problems are a buy/sell state machine; one transaction needs only a running minimum.
0/1 knapsack / subset — practice problems#
- Subset sum equals to target — 1D tabulation, t descending: dp[t] | = dp[t − x] O(n·k)
- Partition equal subset sum — 1D boolean DP: dp[t] | = dp[t − x], t descending O(n·S)
- Partition a set into two subsets with minimum absolute sum difference — Boolean row + scan: dp[t] for t ≤ S/2, take the largest true O(n·S)
- Count subsets with sum K — 1D counting DP: dp[t] += dp[t − x], t descending O(n·k)
- Count partitions with given difference — 1D counting DP: findWays(arr, (S+d)/2) O(n·S)
- 0 and 1 Knapsack — 1D tabulation, w descending: dp[w] = max(dp[w], v + dp[w − wt]) O(n·W)
- Target sum — Count subsets with sum (S + target)/2: reduction + 1D counting O(n·S)
- Largest divisible subset — Sort + LIS-style dp + parent: dp[i] = 1 + max dp[j] with a[i] % a[j] == 0 O(n²)
- Palindrome partitioning II — Front partition + isPal table: O(1) palindrome lookups O(n²)
- Partition array for maximum sum — Bottom-up suffix dp: i from n−1 down O(n·k)
Check yourself 2 questions
Subset sum transition?
Show answer
dp[t] |= dp[t − x], t descending.
Partition equal subset reduces to?
Show answer
Subset sum to total ÷ 2.
Takeaway Subset sum and partitions use 1D boolean DP with t descending.
Unbounded knapsack — practice problems#
- Minimum coins — 1D tabulation, target ascending: dp[t] = min(dp[t], 1 + dp[t − c]) O(n·amount)
- Coin change II — 1D tabulation, coins outer: dp[t] += dp[t − c], t ascending O(n·amount)
- Unbounded knapsack — 1D tabulation, capacity ascending: dp[w] = max(dp[w], v + dp[w − wt]) O(n·W)
- Rod cutting problem — Unbounded knapsack table: items = lengths, capacity = n O(n²)
Check yourself 2 questions
Minimum coins transition?
Show answer
dp[t] = min(dp[t], 1 + dp[t − c]), t ascending.
Why coins in the outer loop for coin change II?
Show answer
To count combinations, not permutations.
Takeaway Unbounded knapsack loops t ascending; coin change II puts coins in the outer loop to count combinations.
LIS family — practice problems#
- Longest increasing subsequence — Tails + binary search: lower_bound replace or append O(n log n)
- Print longest increasing subsequence — dp + parent array: parent[i] = best predecessor O(n²)
- Largest divisible subset — Sort + LIS-style dp + parent: dp[i] = 1 + max dp[j] with a[i] % a[j] == 0 O(n²)
- Longest string chain — Sort + hash of deletions: dp[w] = 1 + max dp[w without char i] O(n·L²)
- Longest bitonic subsequence — Two O(n²) LIS passes: front[i] + back[i] − 1 O(n²)
- Number of longest increasing subsequences — dp + cnt arrays: reset on longer, add on equal O(n²)
- Matrix chain multiplication — Bottom-up interval table: i from n−1 down, j from i+1 up O(n³)
Check yourself 2 questions
LIS O(n log n) method?
Show answer
A tails array with lower_bound replace or append.
Is the tails array the LIS itself?
Show answer
No, only its length is meaningful.
Takeaway LIS in O(n log n) with tails and binary search; printing needs a parent array.
Two strings (LCS/edit) — practice problems#
- Longest common subsequence — Two-row tabulation: prev / cur rows over prefixes O(n·m)
- Longest common substring — Ending-at DP, two rows: match → diag + 1, else 0; track max O(n·m)
- Longest palindromic subsequence — LCS(s, reverse(s)), two rows: reuse LCS O(n²)
- Minimum insertions to make string palindrome — n − LCS(s, reverse(s)): reuse LPS O(n²)
- Shortest common supersequence — LCS table + backward walk: match → emit once, else emit the dropped char O(n·m)
- Distinct subsequences — 1D DP, j descending: dp[j] += dp[j−1] on match O(n·m)
- Edit distance — Two-row tabulation: prev / cur with cur[0] = i O(n·m)
- Wildcard matching — Two-row tabulation: prev = pattern row i−1 O(n·m)
- Count palindromic subsequences — Bottom-up interval table: i descending, j ascending O(n²)
Check yourself 2 questions
Longest common substring: mismatch transition?
Show answer
Reset to 0.
Longest palindromic subsequence trick?
Show answer
LCS of the string and its reverse.
Takeaway LCS, longest common substring, palindromic subsequence and edit distance all use (i, j) states with two rows.
Interval / partition (MCM) — practice problems#
- Maximum sum of non adjacent elements — Space-optimised tabulation: prev = dp[i−1], prev2 = dp[i−2] O(n)
- Matrix chain multiplication — Bottom-up interval table: i from n−1 down, j from i+1 up O(n³)
- Minimum cost to cut the stick — Bottom-up interval table: by increasing gap j − i O(m³)
- Burst balloons — Bottom-up interval table: i descending, j ascending O(n³)
- Evaluate boolean expression to true — Bottom-up T / F tables: i descending over symbols, j ascending O(n³)
- Palindrome partitioning II — Front partition + isPal table: O(1) palindrome lookups O(n²)
- Partition array for maximum sum — Bottom-up suffix dp: i from n−1 down O(n·k)
Check yourself 2 questions
MCM fill order?
Show answer
i from n−1 down, j from i+1 up (by interval length).
MCM complexity?
Show answer
O(n³).
Takeaway Matrix chain and partition problems fill an interval table by length, O(n³).
Tree / bitmask / graph DP (DP-patterns)#
- Diameter: L height + R height at each node
- Max path sum: drop negative children (max(0, ·))
- Binary Tree Cameras: states 0 needs, 1 has, 2 covered
- Distribute coins: return surplus/deficit; moves += |L| + |R|
- House Robber III: return [rob, skip]
- TSP / visit all nodes: dp(mask, last); BFS + mask for shortest
- Partition to K equal subsets: mask + remaining, reset at 0
- Cheapest flights K stops: (node, stops) — Bellman-Ford K+1 rounds
- Longest path in DAG: relax in topological order
Check yourself 2 questions
Binary Tree Cameras states?
Show answer
0 needs a camera, 1 has one, 2 covered.
Max path sum: how are negative children handled?
Show answer
Dropped with max(0, ·).
Takeaway Tree DP returns states from children; bitmask DP encodes subsets; graph DP follows DAG order.
0/1 knapsack recursion tree (DP-patterns)#
flowchart TD
A["Knapsack(i, W=3)"] --> B["Exclude: Knapsack(i-1, 3)"]
A --> C["Include: 3 + Knapsack(i-1, 1)"]
C --> D["base: no items left → 0"]Check yourself 2 questions
Two branches at each knapsack node?
Show answer
Exclude the item, or include it (if it fits).
Base case?
Show answer
No items left: value 0.
Takeaway Each item branches into exclude and include; memoising the (i, W) states removes repeats.
Fibonacci overlap → memo (DP-patterns)#
flowchart TD
A["F(4)"] --> B["F(3)"]
A --> C["F(2) ⟵ repeated"]
B --> D["F(2) ⟵ repeated"]
B --> E["F(1)"]
C --> F["F(1)"]
C --> G["F(0)"]Check yourself 2 questions
Why is naive Fibonacci exponential?
Show answer
It recomputes the same subproblems repeatedly.
Fix?
Show answer
Memoise or tabulate: O(n).
Takeaway Naive Fibonacci repeats subproblems; memoisation computes each once.
Stock state machine#
stateDiagram-v2
[*] --> Rest
Rest --> Hold: buy (−p)
Hold --> Sold: sell (+p − fee)
Sold --> Rest: cooldown 1 day
Hold --> Hold: keep
Rest --> Rest: waitCheck yourself 2 questions
What does the cooldown transition do?
Show answer
Sold must wait a day before returning to rest.
Where is a transaction fee charged?
Show answer
On the sell transition.
Takeaway Rest, hold, sold: buy moves rest to hold, sell moves hold to sold, cooldown returns to rest.
Common DP mistakes#
- Wrong knapsack direction — backward 0/1, forward unbounded
- dp[0] = 1 vs 0 — derive from the definition, don't guess
- LIS O(n log n): tails is NOT the LIS — only len(tails)
- Interval DP: fill by increasing length, not by l or r
- 2D string DP: s1[i−1] aligns with dp[i] (empty-string base row)
- Max product subarray: track max AND min — negatives flip
- Target sum: (S + target) must be even and ≥ 0
- Burst balloons: choose the LAST balloon to burst in (i, j)
Check yourself 2 questions
Knapsack loop direction rule?
Show answer
Backward for 0/1, forward for unbounded.
Interval DP fill order?
Show answer
By interval length.
Takeaway Wrong knapsack direction, guessed base cases, confusing LIS tails with the LIS, and interval DP filled in the wrong order.
10Dynamic programming — 11 patterns
DP-patterns/*/README.md, DP-patterns/recursion/README.md, Coding/striver-a2z DP tables
DP family map#
4-step method (recursion → DP)#
- 1. State: what changes? (index, capacity, last pick, mask)
- 2. Choices: take / skip / which split point
- 3. Base cases: index out of range, capacity 0
- 4. Memo → tabulate → space-optimise (keep only prev row)
| Family | State · transition |
|---|---|
| 0/1 knapsack | dp[i][w]=max(dp[i-1][w], v+dp[i-1][w-wt]); 1D: iterate w descending |
| Unbounded | same but dp[i][w-wt]; 1D iterate w ascending |
| Coin ways | loop coins outer → combinations; amount outer → permutations |
| LCS | match → 1+diag; else max(up,left) |
| Edit distance | match → diag; else 1+min(ins,del,rep) |
| LPS | LCS(s, reverse(s)); min deletions = n−LPS |
| SCS | m+n−LCS |
| LIS | O(n log n): tails + bisect_left; print → parent array |
| Russian doll | sort w asc, h desc, LIS on h |
| Kadane circular | max(maxK, total−minK) unless all negative |
| Max product | track max & min (negatives flip) |
| Stocks w/ k | buy[k], sell[k] state machine; cooldown/fee variants |
| MCM / interval | dp[i][j]=min over k; fill by length |
| Burst balloons | k = last balloon burst in (i,j) |
| Dungeon | fill from bottom-right: need = max(1, min(next)−cell) |
| Cherry pickup | two walkers at once: (r1,c1,r2), c2=r1+c1−r2 |
| Tree DP | return (rob, notRob) pair |
| Bitmask TSP | dp[mask][last], O(2^n·n²) |
| Partition K equal | bitmask + bucket fill, or backtrack with sort desc |
Check yourself 2 questions
What defines the state?
Show answer
What changes between calls: index, capacity, last pick, mask.
Order of optimisation?
Show answer
Memoise, tabulate, then optimise space.
Takeaway State, choices, base cases, then memo → tabulate → space-optimise.
Advanced DP templates#
| Family | State | Transition | Classic problems |
|---|---|---|---|
| Digit DP | (position, tight, started, extra such as sum or mask) | Try each digit up to limit (the bound's digit if tight, else 9) | Count numbers ≤ N with digit sum S, no repeated digits, numbers with a given count of 1s |
| Bitmask DP | dp[mask][last] over subsets, n ≤ ~20 | Add one unvisited element to the mask | Travelling salesman, assign tasks to workers, shortest superstring |
| Rerooting | down[v] from children, then up[v] from the parent's side | Two DFS passes; answer at v combines both | Sum of distances in tree, best root for some metric |
| DP on DAGs | Value per node in topological order | Relax all outgoing edges | Longest path, count paths, course schedule with durations |
| Probability / expectation | Expected value from a state | Weighted sum of next states' expectations | Knight probability, dice games, soup servings |
| Reconstructing the answer | Store the choice made at each state | Walk choices back from the final state | Print the LCS, the knapsack items, the edit operations |
from functools import lru_cache def count_digit_sum(N, S): # how many x in [0, N] have digit sum == S digits = list(map(int, str(N))) @lru_cache(maxsize=None) def go(i, tight, total): if total > S: return 0 if i == len(digits): return int(total == S) limit = digits[i] if tight else 9 return sum(go(i + 1, tight and d == limit, total + d) for d in range(limit + 1)) return go(0, True, 0)
Check yourself 2 questions
Digit DP state?
Show answer
(position, tight, started, extra such as sum or mask).
Classic digit DP problem?
Show answer
Count numbers ≤ N with a digit property.
Takeaway Digit DP, bitmask DP, interval DP and tree DP each have a standard state and transition.
Problem list per pattern (from DP-patterns/)
| Pattern | Problems |
|---|---|
| 0/1 Knapsack | subset sum, equal subset partition, count subsets with sum, min subset sum diff, target sum, count subsets with given diff |
| Unbounded | coin change (ways, min coins), rod cutting, min cost tickets, perfect squares, word break, integer break |
| LCS | longest common substring, edit distance, LPS, SCS, distinct subsequences, min insert/delete to convert, wildcard / regex matching |
| LIS | max sum increasing subseq, Russian doll, bitonic, box stacking, building bridges, largest divisible subset, number of LIS |
| Kadane | max subarray, circular, max product, stocks I/II/III/IV, cooldown, fee |
| MCM | matrix chain, burst balloons, palindrome partitioning II, boolean parenthesization, optimal BST, min cost to cut stick |
| Grid | unique paths I/II, min path sum, triangle, dungeon game, gold mine, cherry pickup, max falling path |
| Trees | house robber III, max path sum, diameter, binary tree cameras |
| Graphs | DAG longest path, course schedule, cheapest flights within K stops (Bellman-Ford K rounds), Hamiltonian path |
| Bitmask | TSP, min incompatibility, assign workers/bikes, partition into K equal subsets |
11Recursion & backtracking decision trees
DP-patterns/recursion/README.md (+easy/medium/hard), practice/dfs.md, practice/imp.md, striver-a2z/18-recursion
Which recursion shape? (18-recursion README)#
flowchart TD
S["Generate / count / check all…"] --> Q1{{Choices per element?}}
Q1 -->|"take or skip"| PN["Pick / not-pick<br/>2ⁿ leaves · subsets, sum-K"]
Q1 -->|"which element next"| FL["for i in start..n−1<br/>combinations, partitions"]
Q1 -->|"which value for this cell"| BC["place → check → recurse → undo<br/>N-Queens, Sudoku, m-colouring"]
PN --> Q2{{Output?}}
Q2 -->|"all"| A["copy path at leaf"]
Q2 -->|"any one"| B["return bool, stop at first true"]
Q2 -->|"count"| C["return left + right"]
FL --> Q3{{Duplicates in input?}}
Q3 -->|yes| D["sort; skip i > start && a[i] == a[i−1]"]
BC --> Q4{{Grid path?}}
Q4 -->|yes| G["mark cell, 4-dir DFS, unmark"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q1,Q2,Q3,Q4 decCheck yourself 2 questions
Pick/not-pick leaf count?
Show answer
2ⁿ.
Which shape avoids duplicate combinations?
Show answer
The for-loop from start, skipping equal values at the same depth.
Takeaway Take or skip → pick/not-pick; which element next → for-loop from start; arrangements → permutations with used flags.
How to solve any recursion (DP-patterns/recursion)#
- Base case — simplest input solved immediately
- Recursive step — smaller subproblem of the same type
- Combine the sub-results
- Trust the recursion for smaller inputs
- What am I tracking on the way down? (path, remaining target, depth)
- What do I return on the way up? (value, True/False, nothing)
- Do I need to undo? (path.pop(), restore grid cell)
path[:] · every append has a popdef backtrack(start, path): if done(path): res.append(path[:]); return for i in range(start, n): if i > start and a[i] == a[i-1]: continue # dups (sorted) if violates(a[i]): continue # prune path.append(a[i]) # choose backtrack(i + 1, path) # i → reuse allowed path.pop() # unchoose
Check yourself 2 questions
Four parts of a recursive solution?
Show answer
Base case, recursive step, combine results, trust the recursion.
One DFS question to ask?
Show answer
What am I tracking on the way down?
Takeaway Base case, smaller subproblem, combine, and trust the recursion.
Pick / not-pick decision tree (subsets of [1,2])#
flowchart LR
A["f(0, [])"] -->|pick 1| B["f(1, [1])"]
A -->|skip 1| C["f(1, [])"]
B -->|pick 2| D["[1,2]"]
B -->|skip 2| E["[1]"]
C -->|pick 2| F["[2]"]
C -->|skip 2| G["[ ]"]Check yourself 2 questions
Leaves for [1, 2]?
Show answer
[1,2], [1], [2], [].
How many subsets for n elements?
Show answer
2ⁿ.
Takeaway Each element is picked or skipped, giving every subset as a leaf.
For-loop (combinations) decision tree#
flowchart TD
A["start=0, path=[]"] --> B["take a0"]
A --> C["take a1"]
A --> D["take a2"]
B --> E["take a1"]
B --> F["take a2"]
C --> G["take a2"]Check yourself 2 questions
Why start from index start?
Show answer
To avoid revisiting earlier elements and duplicating combinations.
Name a problem using this shape.
Show answer
Combination sum, or subsets with duplicates.
Takeaway Each level chooses the next element from start onward, so combinations come out once each.
Place → check → recurse → undo (N-Queens)#
flowchart TD
A["row 0"] --> B["col 0 safe? place"]
B --> C["row 1: try cols"]
C --> D["conflict → undo, next col"]
C --> E["safe → row 2 …"]
E --> F["row == n → record board"]Check yourself 2 questions
When is a board recorded?
Show answer
When row == n.
What happens on conflict?
Show answer
Undo and try the next column.
Takeaway Place, check safety, recurse to the next row, undo on conflict; record at row n.
Roadmap — easy#
- Factorial · Fibonacci · Sum of digits · Power(x, n) · Reverse string · Palindrome · Count set bits · Array sum · Recursive binary search · String length
Check yourself 2 questions
Name two easy recursion problems.
Show answer
Any two of: factorial, Fibonacci, sum of digits, power, reverse string, palindrome, recursive binary search.
Why start with these?
Show answer
They practise base case and smaller-subproblem thinking.
Takeaway Factorial, Fibonacci, digits, power, reversal and recursive binary search build recursion basics.
Roadmap — medium#
- Subsets · Permutations · Tower of Hanoi · Combination sum · Phone letters · Generate parentheses · Subset sum · Josephus · atoi · Tree traversals
Check yourself 2 questions
Name two medium recursion problems.
Show answer
Any two of: subsets, permutations, Tower of Hanoi, combination sum, phone letters, generate parentheses.
Which classic moves n disks with recursion?
Show answer
Tower of Hanoi.
Takeaway Subsets, permutations, Hanoi, combination sum and parentheses generation build backtracking skill.
Roadmap — hard#
- N-Queens · Sudoku · Word Search II · Palindrome partitioning · Wildcard / Regex matching · Flatten nested list · K-th permutation · Rat in a maze · M-colouring
Check yourself 2 questions
Name two hard recursion problems.
Show answer
Any two of: N-Queens, Sudoku, Word Search II, palindrome partitioning, wildcard or regex matching.
Which structure speeds up Word Search II?
Show answer
A trie.
Takeaway N-Queens, Sudoku, Word Search II, palindrome partitioning and regex matching are the hard set.
Your striver recursion problems (18-recursion + 12-basic-recursion)
- Pow(x, n) — Iterative binary exponentiation: walk the bits of n; square x each step, multiply when the bit is set O(log n)
- Generate Parentheses — Backtracking on open/close counts: '(' if open < n; ')' if close < open O(4ⁿ / √n)
- Power Set — Pick / not-pick recursion: at index i: recurse without nums[i], then with it O(n · 2ⁿ)
- Count Good Numbers — Fast modular power: pow(5, ⌈n/2⌉) · pow(4, ⌊n/2⌋) mod p O(log n)
- Reverse a Stack — Recursion with insert-at-bottom: pop top, reverse rest, insert top at bottom O(n²)
- Check if There Exists a Subsequence with Sum K — 1D subset-sum DP: can[s] | = can[s − x], s from k down to x O(n · k)
- Count All Subsequences with Sum K — 1D counting DP: ways[s] += ways[s − x], s from k down to x O(n · k)
- Generate Binary Strings Without Consecutive 1s — Backtracking with last-char check: always try 0; try 1 only if the previous char is 0 O(n · Fib(n))
- Combination Sum — Loop-based backtracking (sorted, with break): for j in [start, n): take c[j], recurse from j O(2^(t/m) · t)
- Combination Sum II — Loop backtracking with sibling skip: sort; skip c[j] == c[j−1] when j > start; recurse j + 1 O(2ⁿ · n) worst
- Subsets I (Subset Sums) — Recursion with running sum: go(i, s): skip → go(i+1, s); take → go(i+1, s + a[i]) O(2ⁿ)
- Subsets II — Loop backtracking, record every node: record cur; for j ≥ i: skip equal siblings, push, recurse j + 1 O(n · 2ⁿ)
- Combination Sum III — Backtracking in increasing order: for d in start..9: if d > rem break; push; recurse d + 1 O(C(9, k) · k)
- Letter Combinations of a Phone Number — Backtracking per digit: go(i): for ch in map[digits[i]]: push, go(i + 1), pop O(4ⁿ · n)
- Palindrome Partitioning — Backtracking + palindrome table: isPal[i][j] DP, then the same backtracking with O(1) checks O(n · 2ⁿ)
- Word Search — DFS marking the board in place: board[r][c] = '#' during the visit, restore after O(m·n·3^L)
- N-Queens — Row recursion with column/diagonal sets: cols[c], diag[r − c + n − 1], anti[r + c] O(n!)
- Rat in a Maze — DFS in D, L, R, U order: direction arrays in alphabetical order → sorted output O(3^(n²) · n²)
- M-Coloring Problem — Backtracking vertex by vertex: for colour c in 1..m: if safe(v, c) → assign, recurse, undo O(mⁿ) worst
- Sudoku Solver — Backtracking with constraint tables: row/col/box used-digit tables; recurse over the list of empty cells O(9^E)
- Expression Add Operators — Backtracking with value and last term: go(i, value, last): pick operand num[i..j], try +, −, * O(n · 4ⁿ)
- Sort a stack using recursion — Pure recursion (sort + insertSorted): pop x, sort rest, insert x in place O(n²)
- Sum of First N Numbers — Functional recursion: return N + f(N − 1) O(N)
- Factorial of a Given Number — Functional recursion: return n · f(n − 1) O(n)
- Sum of Array Elements — Optimal — recursion on an index: f(i) = nums[i] + f(i + 1) O(n)
- Reverse a String (Recursive) — Optimal — swap ends, recurse inward: swap(l, r); f(l + 1, r − 1) O(n)
- Check if String is Palindrome or Not — Optimal — recurse on (l, r): s[l]==s[r] and f(l+1, r−1) O(n)
- Check if a Number is Prime or Not — Optimal — recurse over 2..√n: stop when i·i > num O(√n)
- Reverse an Array (Recursive) — Single index i: swap(i, n−1−i); f(i + 1) O(n)
- Check if the Array is Sorted — Optimal — adjacent pairs recursively: nums[i] ≤ nums[i+1] and f(i + 1) O(n)
- Sum of Digits in a Given Number — Optimal — % 10 recursion: n % 10 + f(n // 10) O(d) = O(log n)
- Fibonacci Number — Optimal — bottom-up, two variables: roll (a, b) → (b, a + b) O(n)
12Backtracking, gotchas, follow-up chains
Coding/03-patterns/patterns-master.md
Backtracking template#
def bt(start, path): res.append(path[:]) # subsets: record every node for i in range(start, n): if i>start and a[i]==a[i-1]: continue # skip dups (sorted) path.append(a[i]) bt(i+1, path) # i (not i+1) → reuse allowed path.pop()
- Permutations:
used[]array, loop from 0 - N-Queens: cols / diag (r−c) / anti-diag (r+c) sets
- Sudoku: try 1–9, validate row/col/box
- Word search: mark cell, restore after
Check yourself 2 questions
How do you skip duplicates?
Show answer
Sort, then skip when i > start and a[i] == a[i−1].
Why append a copy of path?
Show answer
Because path is mutated afterwards.
Takeaway Record, loop from start, skip duplicates at the same depth, choose, recurse, undo.
Gotchas (patterns-master)#
- Negatives break sliding window → prefix sums
- Skip duplicates only at the same depth:
i>start - Tree DP returns one arm, global uses both
- Dijkstra: skip if popped dist > dist[node]
- Binary search on answer: prove monotonic feasibility first
- Greedy needs an exchange argument; else DP
- Interval merge: sort by start; non-overlap count: sort by end
Check yourself 2 questions
Sliding window with negatives: what instead?
Show answer
Prefix sums.
Where should duplicate-skipping happen?
Show answer
Only at the same depth: i > start.
Takeaway Negatives break windows, skip duplicates only at the same depth, tree DP returns one arm, skip stale Dijkstra entries.
Follow-up chains#
| Start | Likely follow-up |
|---|---|
| Two Sum | sorted → 2 ptr; 3Sum/4Sum; BST input; stream (design) |
| Sliding window | at most K → exactly K; with negatives |
| Binary search | rotated; duplicates; 2D matrix; on answer |
| Tree DFS | iterative; return path; O(1) space (Morris) |
| Linear DP | space-optimise; print solution; k transactions |
| Backtracking | duplicates; count only (→ DP); prune |
| Graph BFS | weighted → Dijkstra; multi-source; bidirectional |
| Intervals | insert; min rooms; free time |
| Heap | stream; k sorted lists; lazy deletion |
Check yourself 2 questions
Likely follow-up to Two Sum?
Show answer
Sorted input with two pointers, then 3Sum/4Sum, BST input, or a streaming design.
Follow-up to 'at most K' windows?
Show answer
Exactly K, or with negatives.
Takeaway Interviewers chain follow-ups: sorted input, k-sums, streams, negatives, duplicates, 2D and on-answer variants.
13Data-structure operations
practice/data_structures/*.py, java-python/reference/01_CHEATSHEET.md; Big-O column = standard values
Data-structure operations#
| Structure | Access | Search | Insert | Delete | Python | Java |
|---|---|---|---|---|---|---|
| Array / list | O(1) | O(n) | O(1) end, O(n) mid | O(n) | list | int[] / ArrayList |
| Hash map / set | — | O(1) avg | O(1) avg | O(1) avg | dict / set / Counter | HashMap / HashSet |
| Stack | top O(1) | O(n) | push O(1) | pop O(1) | list append/pop | ArrayDeque push/pop |
| Queue / deque | ends O(1) | O(n) | O(1) | O(1) | collections.deque | ArrayDeque offer/poll |
| Heap | min O(1) | O(n) | O(log n) | pop O(log n) | heapq (min only) | PriorityQueue |
| Linked list | O(n) | O(n) | O(1) at node | O(1) at node | custom Node | custom / LinkedList |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) | sortedcontainers / bisect | TreeMap / TreeSet |
| Trie | — | O(L) | O(L) | O(L) | nested dict | Node[26] |
| DSU | — | find ≈O(1) | union ≈O(1) | — | parent list | int[] parent |
| Segment tree | — | query O(log n) | update O(log n) | — | array 4n | int[4n] |
| Fenwick (BIT) | — | prefix O(log n) | add O(log n) | — | tree[n+1], i += i & −i | same |
Check yourself 2 questions
Hash map average lookup?
Show answer
O(1).
Insert in the middle of an array?
Show answer
O(n).
Takeaway Know access, search, insert and delete costs, and the Python and Java names, for each structure.
Fenwick tree#
class FenwickTree: # 1-indexed inside def __init__(self, n): self.n = n; self.tree = [0]*(n+1) def update(self, i, delta): i += 1 while i <= self.n: self.tree[i] += delta; i += i & -i def prefix_sum(self, i): # sum [0, i] i += 1; s = 0 while i > 0: s += self.tree[i]; i -= i & -i return s # range_sum(l, r) = prefix_sum(r) - prefix_sum(l-1)Triggers: range sum + point updates → Fenwick; range update → lazy segment tree; static RMQ → sparse table
Beyond range sums
- Range update, point query: add v at l and −v at r+1; the value is a prefix sum.
- Count inversions: scan right to left over compressed ranks; query smaller ranks, then add.
- k-th smallest: binary lifting over powers of two finds it in O(log n).
- 2D Fenwick: point updates and rectangle sums in O(log² n).
Check yourself 2 questions
Update step in a Fenwick tree?
Show answer
i += i & −i.
Query step?
Show answer
i −= i & −i.
Takeaway A Fenwick tree does point updates and prefix sums in O(log n) using i += i & −i.
Design-a-data-structure problems#
| Problem | Core structure | The trick | Cost |
|---|---|---|---|
| Min stack | Stack of (value, min so far) | Each entry remembers the minimum at the time it was pushed | O(1) all ops |
| Queue using stacks | In-stack + out-stack | Pour in → out only when out is empty | Amortised O(1) |
| LRU cache | Hash map + doubly linked list | Move to front on access; evict from the tail | O(1) |
| LFU cache | Key map + frequency → linked list + minFreq | On access, move the key to the next frequency list; evict from minFreq's tail | O(1) |
| Insert, delete, getRandom O(1) | Array + value → index map | Delete by swapping with the last element, then pop | O(1) |
| Hit counter (last 5 minutes) | Circular buffer of 300 (time, count) or a deque | Overwrite a slot when its timestamp is stale | O(1) / O(window) |
| Time-based key-value store | Map key → list of (timestamp, value) | Timestamps arrive increasing, so binary search for the last ≤ t | O(log n) get |
| Snapshot array | Per index: list of (snap_id, value) | Only record changes; binary search by snap_id | O(log s) get |
| Median of a stream | Max-heap low half + min-heap high half | Rebalance so sizes differ by at most one | O(log n) add, O(1) median |
| Iterators (peeking, BST, flatten nested list) | Cached next element / stack of the left spine / stack of iterators | Prepare the next item lazily in hasNext() | Amortised O(1) |
| Design Twitter feed | Per-user tweet lists + heap merge | Merge the latest tweets of followees with a heap of size k | O(f log f) per feed |
| Range sum with updates | Fenwick tree or segment tree | Point update + prefix query | O(log n) |
| Circular queue / deque | Fixed array + head index + size | Index with (head + i) % capacity | O(1) |
| Hash map from scratch | Array of buckets with chaining | Hash then mod capacity; resize ×2 at load factor ~0.75 | O(1) average |
| Autocomplete | Trie storing the top-k suggestions per node | Update top-k lists on insert; a query is one walk | O(prefix length) |
Check yourself 2 questions
Min stack trick?
Show answer
Each entry stores the minimum at push time.
LRU cache structure?
Show answer
A hash map plus a doubly linked list.
Takeaway Min stack, queue via stacks, LRU cache and similar designs each hinge on one trick.
14Java vs Python quick syntax
java-python/reference/01_CHEATSHEET.md, 02_ERRORS.md; Python column written to match
Java ↔ Python for DSA#
| Need | Python | Java |
|---|---|---|
| map count | cnt[k] = cnt.get(k, 0) + 1 | map.merge(k, 1, Integer::sum) |
| get default | d.get(k, 0) | map.getOrDefault(k, 0) |
| list | a = []; a.append(x); len(a) | List<Integer> a = new ArrayList<>(); a.add(x); a.size() |
| array | [0]*n; len(a) | int[] a = new int[n]; a.length (no parens) |
| stack | st.append(x); st.pop(); st[-1] | Deque<Integer> st = new ArrayDeque<>(); push/pop/peek |
| queue | q = deque(); q.append; q.popleft() | Queue<Integer> q = new LinkedList<>(); offer/poll/peek |
| min-heap | heapq.heappush(h, x) | new PriorityQueue<>() |
| max-heap | push -x | new PriorityQueue<>(Comparator.reverseOrder()) |
| sort by key | a.sort(key=lambda p: (p.city, p.name)) | list.sort(Comparator.comparing(Person::city).thenComparing(Person::name)) |
| sort array | a.sort() (returns None!) | Arrays.sort(a) |
| string build | ''.join(parts) | StringBuilder sb; sb.append(x); sb.toString() |
| char at | s[i] | s.charAt(i) |
| substring | s[1:4] | s.substring(1, 4) |
| equality | == | s.equals(t) (== compares references) |
| int division | 5 // 2 | 5 / 2 == 2; (double) 5 / 2 |
| iterate map | for k, v in d.items() | for (Map.Entry<K,V> e : map.entrySet()) |
Check yourself 2 questions
Java equivalent of cnt[k] = cnt.get(k, 0) + 1?
Show answer
map.merge(k, 1, Integer::sum).
Java equivalent of d.get(k, 0)?
Show answer
map.getOrDefault(k, 0).
Takeaway Map counts, defaults, lists and heaps have direct Python and Java equivalents.
Gotchas that cost an hour each (java-python/reference)#
- Java "a" == "b" compares references — use .equals()
- Integer 128 == 128 is FALSE — cache only -128..127
- List.of(..) is immutable — .add() throws
- int / int truncates: 5/2 == 2
- array.length (no parens) vs String.length() vs List.size()
- Modifying a list in for-each → ConcurrentModificationException; use Iterator / removeIf
- Python: arr = arr.sort() → None
- Python: def f(a=[]) shared default; recursion limit → sys.setrecursionlimit
- Java mid overflow: lo + (hi - lo) / 2
- Java:
Arrays.asList(int[])gives aList<int[]>, not a list of integers - Java:
list.remove(1)removes index 1;list.remove(Integer.valueOf(1))removes the value - Java: comparator
(a, b) -> a - boverflows; useInteger.compare(a, b) - Java:
Math.abs(Integer.MIN_VALUE)is still negative; widen tolong - Java:
'a' + 1is anint; cast back with(char) ('a' + 1) - Python:
[[0] * n] * mshares one row m times; use[[0] * n for _ in range(m)] - Python:
heapqis a min-heap only; push negatives for a max-heap - Python
-7 // 2 == -4(floors) but Java-7 / 2 == -3(truncates);%differs too
Check yourself 2 questions
Why is Integer 128 == 128 false in Java?
Show answer
Only −128 to 127 are cached; == compares references.
How should strings be compared in Java?
Show answer
With .equals().
Takeaway String ==, Integer caching, immutable List.of and integer division bite Java coders.
15Problem finder — 434 problems (filterable)
Coding/striver-a2z/*/*.md — ‘Approaches at a glance’ (last row), ‘Common mistakes’ (first), ‘Interview angle’
Problem bank: 434 problems#
Every problem from the Striver A2Z sheet with the best approach, complexity, the common mistake and what to say in the interview. Filter by topic or type a name or technique.
| Topic | Problem | Best approach — idea | Time | Space | Common mistake | Interview angle |
|---|---|---|---|---|---|---|
| Basic maths | Count All Digits of a Number | Optimal — logarithm — ⌊log₁₀ n⌋ + 1 | O(1) | O(1) | Forgetting the n == 0 case. | Say up front that 0 is a special case. That one sentence shows you test boundaries before coding. |
| Basic maths | Count Number of Odd Digits in a Number | Optimal — digit loop — d = n % 10; test parity | O(log₁₀ n) | O(1) | Checking n % 2 (the parity of the whole number) instead of d % 2. | |
| Basic maths | Reverse a Number | Optimal — arithmetic build — rev = rev*10 + d | O(log₁₀ n) | O(1) | Accumulating in int, which silently wraps on overflow. | This problem tests overflow awareness. Say "the reverse can exceed INT_MAX, so I'll accumulate in a long" before you write the loop. |
| Basic maths | Palindrome Number | Optimal — reverse half — stop when rev ≥ n | O(log₁₀ n) | O(1) | Running the half-reverse without the trailing-zero guard. For 10: step 1 → n = 1, rev = 0; step 2 → n = 0, rev = 1; then rev // 10 == 0 == n wrongly returns true. | |
| Basic maths | Return the Largest Digit in a Number | Optimal — digit loop — best = max(best, n % 10) | O(log₁₀ n) | O(1) | Initialising best = -1 and then returning -1 for n = 0. | |
| Basic maths | Factorial of a Given Number | Optimal — iterative product — res *= i for i in 2..n | O(n) | O(1) | Starting res = 0, which makes every answer 0. | Say the overflow boundary aloud: "12! is the last that fits in int and 20! the last that fits in long, so I'll return long." If they push for larger n, offer % (10⁹+7) or a big-integer type. |
| Basic maths | Check if the Number is Armstrong | Optimal — two digit loops — count k, then sum dᵏ | O(d · log k) ≈ O(log n) | O(1) | Always cubing (d³) instead of raising to the digit count k. | |
| Basic maths | Check for Perfect Number | Optimal — √n pairs — sum i and n/i for i ≤ √n | O(√n) | O(1) | Including n itself in the sum, by starting with s = 1 + n or looping from i = 1 and adding n / 1. | |
| Basic maths | Check for Prime Number | Optimal — 6k ± 1 — after 2 and 3, test only 6k±1 | O(√n / 3) | O(1) | Writing i * i < n, which misses perfect squares like 25. | If you're asked about many queries, switch to a sieve (next problem). If n is up to 10¹⁸, name Miller–Rabin and don't implement it unless asked. |
| Basic maths | Count of Prime Numbers till N | Optimal — Sieve of Eratosthenes — mark multiples from p² | O(n log log n) | O(n) | Starting marking at 2p instead of p². It's still correct, just slower. | Name both costs. Per-number trial division is O(n√n); the sieve is O(n log log n), essentially linear. Say why marking starts at p²: smaller multiples k·p with k < p were already crossed out by th |
| Basic maths | GCD of Two Numbers | Optimal — modulo Euclid — a, b = b, a % b | O(log min(a,b)) | O(1) | Using the subtraction version in an interview without mentioning its O(max) worst case. | Give the one-line proof: any d dividing a and b also divides a − q·b = a mod b, and the reverse holds too. So the pairs (a, b) and (b, a mod b) have the same common divisors. |
| Basic maths | LCM of Two Numbers | Optimal — via GCD — a / gcd * b | O(log min(a,b)) | O(1) | Computing a * b / g, where a * b overflows even when the LCM fits. | |
| Basic maths | Divisors of a Number | Optimal — two lists — small asc + large desc reversed | O(√n) | O(d) | Adding √n twice for perfect squares. | |
| Basic arrays | Sum of Array Elements | Optimal — accumulator — s += x | O(n) | O(1) | accumulate(..., 0) in C++. The int init makes the whole sum int. | |
| Basic arrays | Count of Odd Numbers in Array | Optimal — bit test — cnt += x & 1 | O(n) | O(1) | x % 2 == 1 in C++/Java, which misses negative odds. | |
| Basic arrays | Check if the Array is Sorted | Optimal — adjacent pairs — first a[i-1] > a[i] → false | O(n) | O(1) | Using >= in the check, which rejects ties. | |
| Basic arrays | Reverse an Array | Optimal — two pointers — swap ends, move inward | O(n) | O(1) | Looping i over the whole array and swapping i with n-1-i, which reverses twice and restores the original. | Say "in place, two pointers, stop when l ≥ r". The common follow-up is rotating by k, which is three reverses, so this function gets reused. |
| Basic hashing | Highest Occurring Element in an Array | Optimal — frequency map — count, then scan entries | O(n) | O(k) distinct | Relying on map iteration order for ties. | Ask about the tie rule before coding. It changes the comparison, and the interviewer is watching whether you clarify. |
| Basic hashing | Second Highest Occurring Element | Optimal — top-2 scan — maintain (f1, e1), (f2, e2) | O(n) | O(k) | Updating e1 = min(e1, x) when e1 = −1 initially. The f > f1 branch fires first (since f ≥ 1 > 0), so it's safe, but only because of that ordering. | Pin down "second highest" first: the second-largest *distinct* frequency, or the second element in sorted order? Striver's version is the distinct-frequency one. |
| Basic hashing | Sum of Highest and Lowest Frequency | Optimal — map, then min/max — one count pass + one scan | O(n) | O(k) | Initialising lo = 0, so the min never updates. | |
| Basic strings | Reverse a String | Optimal — two pointers — swap ends, move inward | O(n) | O(1) | s = s[::-1] in Python rebinds the local name; the caller's list is unchanged. Use s[:] = s[::-1] or s.reverse(). | It's given as a char array because strings are immutable in Python and Java. Ask whether you can modify the input. |
| Basic strings | Palindrome Check | Optimal — two pointers — compare ends, move inward | O(n) | O(1) | Comparing s[i] with s[n − i], which is off by one. | |
| Basic strings | Largest Odd Number in a String | Optimal — rightmost odd + strip zeros — end at the rightmost odd digit, start at the first non-zero | O(n) | O(1) extra | int(s): overflows in C++/Java and is slow for 10⁵ digits in Python. | The trap is converting to an integer: n = 10⁵ digits overflows everything. Say up front that you'll compare by length and position, not numerically. |
| Basic strings | Longest Common Prefix | Optimal — vertical scan — compare column i across all strings | O(S) total chars | O(1) extra | Indexing s[i] before checking i < len(s). | |
| Basic strings | Isomorphic Strings | Optimal — last-seen index arrays — last_s[s[i]] == last_t[t[i]] at every i | O(n) | O(256) | Only one map (s → t), which accepts badc / baba. | The badc / baba case is what interviewers check. A one-direction map passes it wrongly, so say "bijection, check both directions" before coding. |
| Basic strings | Rotate String | Optimal — substring of s + s — goal in s + s | O(n) with KMP; O(n²) worst case naive | O(n) | Dropping the length check. | |
| Basic strings | Valid Anagram | Optimal — count array — +1 for s, −1 for t, all zero | O(n) | O(26) | Comparing character *sets*, which ignores multiplicity. | |
| Basic strings | Sort Characters by Frequency | Optimal — bucket by frequency — bucket[f] ← chars; walk f = n..1 | O(n + Σ) | O(n) | Sorting with key -freq only, which leaves equal-frequency chars interleaved under some sort orders. Add the char as a secondary key. | Say the tie-break out loud. Then offer both versions: a sort by (-freq, char) (O(n + Σ log Σ)) and buckets (O(n)). Σ is tiny, so either is fine, but the bucket version shows you know the trick. |
| Basic recursion | Sum of First N Numbers | Functional recursion — return N + f(N − 1) | O(N) | O(N) stack | Base case N == 1 only, which recurses forever on N = 0. | Write the recursive version because that's what is asked, then mention N(N+1)/2 in O(1). Showing you know the closed form, and the stack cost of the recursion, is the signal. |
| Basic recursion | Factorial of a Given Number | Functional recursion — return n · f(n − 1) | O(n) | O(n) stack | Base case returning 0, which makes every product 0. | |
| Basic recursion | Sum of Array Elements | Optimal — recursion on an index — f(i) = nums[i] + f(i + 1) | O(n) | O(n) stack | Slicing per call (O(n²)). | |
| Basic recursion | Reverse a String (Recursive) | Optimal — swap ends, recurse inward — swap(l, r); f(l + 1, r − 1) | O(n) | O(n) stack + O(n) buffer | Base case l == r only: for even n the pointers cross and never become equal → infinite recursion / out of bounds. | |
| Basic recursion | Check if String is Palindrome or Not | Optimal — recurse on (l, r) — s[l]==s[r] and f(l+1, r−1) | O(n) | O(n) stack | r = len(s) − 1 as a Python default argument: it would be evaluated once at definition time, so use None. | |
| Basic recursion | Check if a Number is Prime or Not | Optimal — recurse over 2..√n — stop when i·i > num | O(√n) | O(√n) stack | Treating 1 as prime. | Lead with the √n bound. The divisor-pair argument (if a·b = n and a ≤ b then a ≤ √n) is the proof interviewers want to hear. |
| Basic recursion | Reverse an Array (Recursive) | Single index i — swap(i, n−1−i); f(i + 1) | O(n) | O(n) stack | Stopping at i >= n instead of n/2: it swaps everything twice and leaves the array unchanged. | |
| Basic recursion | Check if the Array is Sorted | Optimal — adjacent pairs recursively — nums[i] ≤ nums[i+1] and f(i + 1) | O(n) | O(n) stack | >= instead of > in the violation check, which rejects duplicates. | |
| Basic recursion | Sum of Digits in a Given Number | Optimal — % 10 recursion — n % 10 + f(n // 10) | O(d) = O(log n) | O(log n) stack | Python / instead of //: float division never reaches 0 cleanly. | |
| Basic recursion | Fibonacci Number | Optimal — bottom-up, two variables — roll (a, b) → (b, a + b) | O(n) | O(1) | Only n == 1 as the base case: F(0) recurses into negatives. | Write the two-call recursion, draw the tree to show the repeated F(n−2), then memoise, then go to two variables. That sequence is the whole DP story; [Part 28](../28-dynamic-programming/README.md) u |
| Sorting | Selection Sort | Selection sort — swap min of [i, n) into i | O(n²) in every case | O(1) | Swapping every time a smaller nums[j] is found, instead of tracking the index: still correct, but O(n²) swaps. | Selection sort is rarely the answer, but its *minimum number of swaps* property shows up: when writes are expensive (flash memory), or in the "minimum swaps to sort a permutation" puzzle (cycle decomp |
| Sorting | Bubble Sort | Optimised — early exit with swapped — stop after a pass with no swaps | O(n²) worst / avg, O(n) best | O(1) | Inner loop to n − 1 every pass, re-checking the finished tail. | |
| Sorting | Insertion Sort | Shift-based (standard) — hold key, shift larger right, place once | O(n²) worst / avg, O(n) best | O(1) | Checking nums[j] > key before j >= 0, which reads nums[−1] (wraps silently in Python). | Insertion sort is the right answer for tiny or nearly-sorted inputs. TimSort and introsort switch to it below ~16–32 elements. Mention that when you're asked why library sorts are fast. |
| Sorting | Merge Sort | Top-down recursive merge sort — sort(l, m), sort(m+1, r), merge(l, m, r) | O(n log n) best / avg / worst | O(n) temp + O(log n) stack | < instead of <= in the merge: still sorted, but no longer stable. | Write merge as its own function; interviewers reuse it for follow-ups (count inversions, reverse pairs, count of smaller numbers after self, sort a linked list). Say "<= keeps it stable" as you wr |
| Sorting | Quick Sort | Two-pointer partition, pivot at low (Striver's version) + middle/random pivot — i walks right over ≤ pivot, j walks left over > pivot, swap, place pivot at j | O(n log n) avg / best, O(n²) worst (rare with random pivot) | O(log n) avg stack | Missing bounds checks in the i/j scans → index out of range when the pivot is the max or min. | Say the worst case out loud (sorted input with a first/last pivot → O(n²), depth n) and fix it with a random pivot before the interviewer asks. partition on its own is the core of Quickselect (k-th |
| Sorting | Recursive Bubble Sort | Recursive outer loop — one pass, then f(n − 1) | O(n²) worst, O(n) best | O(n) stack | Recursing with n instead of n − 1 → infinite recursion. | |
| Sorting | Recursive Insertion Sort | Head recursion on n (classic) — f(n − 1), then insert nums[n − 1] | O(n²) worst, O(n) best | O(n) stack | Inserting before recursing in the head-recursive version: that inserts into an unsorted prefix. | |
| Arrays | Linear Search | Linear scan — return at the first match | O(n) | O(1) | Returning inside the loop's else branch (−1 after checking only index 0). | |
| Arrays | Largest Element | Single pass — track the running max | O(n) | O(1) | best = 0 → wrong for all-negative input. | |
| Arrays | Second Largest Element | One pass, top-2 tracking — demote first → second on a new max | O(n) | O(1) | elif x > second without x < first → duplicates of the max become the second. | |
| Arrays | Maximum Consecutive Ones | Running streak — cnt++ on 1, cnt = 0 on 0 | O(n) | O(1) | Updating best only when a 0 is seen → misses a trailing run. | |
| Arrays | Left Rotate Array by One | Save first, shift, place — temp = nums[0]; shift left; nums[n−1] = temp | O(n) | O(1) | Not saving nums[0] before overwriting it. | |
| Arrays | Left Rotate Array by K Places | Three reversals — rev(0,k−1), rev(k,n−1), rev(0,n−1) | O(n) | O(1) | Forgetting k %= n → out-of-range indices. | |
| Arrays | Move Zeros to End | Two pointers (write index) — swap each non-zero into position j | O(n) | O(1) | Swapping zeros with the *next* non-zero using nested loops → O(n²). | |
| Arrays | Remove Duplicates from Sorted Array | Two pointers — i = last unique, j scans | O(n) | O(1) | Returning i instead of i + 1. | The grader checks both k and the prefix. Say so, and state that the tail is garbage, so the interviewer knows you understand the contract. |
| Arrays | Find Missing Number | XOR — XOR of 0..n and all nums | O(n) | O(1) | Using n = len + 1 when the range is 0..n (it's 1..n in some variants; read the statement). | |
| Arrays | Union of Two Sorted Arrays | Two-pointer merge with dedupe — take the smaller head; skip if equal to the last output | O(n + m) | O(1) beyond the output | Forgetting to dedupe the leftover tail. | |
| Arrays | Intersection of Two Sorted Arrays | Two pointers — advance the smaller; equal → take and advance both | O(n + m) | O(1) beyond the output | Advancing only one pointer on a match → the same element counted repeatedly. | |
| Arrays | Majority Element I | Boyer–Moore voting — cand/cnt; cancel unequal pairs | O(n) | O(1) | Returning cnt instead of cand. | Boyer–Moore is the expected O(1)-space answer. If the majority is *not* guaranteed, add a second pass that counts the candidate, and say so before you're asked. |
| Arrays | Leaders in an Array | Right-to-left suffix max — leader iff nums[i] > maxRight | O(n) | O(1) beyond the output | >= instead of > (duplicates become leaders). | |
| Arrays | Rearrange Array Elements by Sign | Single pass, two write indices — pos → even slot, neg → odd slot | O(n) | O(n) for the output | Swapping in place: breaks the relative order. | |
| Arrays | Print the Matrix in Spiral Manner | Four boundaries — right, down, left, up; shrink after each side | O(m · n) | O(1) beyond the output | Missing the top <= bottom / left <= right guards → the middle row/column is duplicated. | The bugs are all in non-square inputs. Before coding, say you'll test a single row, a single column and a 3 × 4 matrix, then actually trace one of them. |
| Arrays | Pascal's Triangle I | Running product nCr — res = res·(n − i)/(i + 1), i < k | O(min(k, n − k)) | O(1) | Off-by-one: using C(r, c) instead of C(r − 1, c − 1). | |
| Arrays | Pascal's Triangle II | Incremental product — val = val · (n − k) / (k + 1) | O(r) | O(1) beyond the output | Updating the DP row left to right (it reads values that were already overwritten). | |
| Arrays | Pascal's Triangle III | Additive DP — row[j] = prev[j − 1] + prev[j] | O(n²) | O(1) beyond the output | Inner loop from j = 0, which reads prev[−1]. | |
| Arrays | Rotate Matrix by 90 Degrees | Transpose + reverse rows — swap(m[i][j], m[j][i]) for j > i; reverse each row | O(n²) | O(1) | Transposing the full matrix (j from 0) → swaps everything twice, so nothing changes. | |
| Arrays | Set Matrix Zeroes | First row/column as markers — mat[i][0], mat[0][j] are the flags; col0 for column 0 | O(m · n) | O(1) | Zeroing while scanning → zeros cascade over the whole matrix. | State the three tiers (O(mn) copy → O(m + n) markers → O(1)) and their trade-off before coding the O(1) one. The order of the final fill is the part to say out loud. |
| Arrays | Two Sum | One-pass hash map — seen[value] = index; look up target − x first | O(n) | O(n) | Inserting before checking → an element pairs with itself when x = target / 2. | Ask whether they want indices or just yes/no, and whether the array is sorted. Sorted with two pointers is O(1) space but loses the original indices unless you sort (value, index) pairs. |
| Arrays | 3 Sum | Sort + two pointers — fix i; l = i + 1, r = n − 1; skip duplicates | O(n²) | O(1) beyond the output (sorting aside) | Skipping i duplicates with nums[i] == nums[i + 1], which drops valid triplets like [-1, -1, 2]. | |
| Arrays | 4 Sum | Sort + two fixed + two pointers — i, j loops with skips; l/r on the rest | O(n³) | O(1) beyond the output | 32-bit sum → false matches after overflow. | |
| Arrays | Sort an Array of 0s, 1s and 2s | Dutch National Flag — low/mid/high; 0 → swap low, 1 → skip, 2 → swap high | O(n), one pass | O(1) | mid++ after swapping with high → the swapped-in 2 or 0 is never examined. | |
| Arrays | Kadane's Algorithm: Maximum Subarray Sum | Kadane — cur = max(x, cur + x); best = max(best, cur) | O(n) | O(1) | Seeding best = 0 → returns 0 for all-negative input. | Expect follow-ups: return the subarray itself, the all-negative case, and the divide-and-conquer O(n log n) version. |
| Arrays | Next Permutation | Pivot, swap, reverse — find the dip from the right; swap with the next larger; reverse the suffix | O(n) | O(1) | > instead of >= when finding the pivot → wrong with duplicates. | |
| Arrays | Majority Element II | Extended Boyer–Moore — two candidates; a third value decrements both; verify | O(n) | O(1) | Skipping verification. | |
| Arrays | Find the Repeating and Missing Number | Sum and sum-of-squares equations — x − y and x² − y² → x + y | O(n) | O(1) | int for sums of squares → overflow. | Offer the hash version first, then the math version, then mention XOR. Call out the overflow in the sum of squares (n² · n ≈ 10¹⁵, so use 64-bit). |
| Arrays | Count Inversions | Merge sort with counting — cross inversions += mid − i + 1 when right wins | O(n log n) | O(n) | < instead of <= in the merge → equal pairs counted. | Say why the count can be done during the merge: inversions split into left-only, right-only and cross pairs, and the cross ones are counted cheaply only once both halves are sorted. |
| Arrays | Reverse Pairs | Merge sort + separate counting pass — for each left i, advance j while left[i] > 2·right[j] | O(n log n) | O(n) | Counting inside the merge loop with the merge's comparison (that counts inversions, not reverse pairs). | |
| Arrays | Maximum Product Subarray | Max/min ending here — hi, lo = max/min(x, x·hi, x·lo) | O(n) | O(1) | Tracking only the max (misses negative × negative). | |
| Arrays | Merge Two Sorted Arrays Without Extra Space | Three pointers from the back (LC 88) — largest of nums1[i], nums2[j] goes to k; k−− | O(m + n) | O(1) | Filling from the front → overwrites unread nums1 elements. | Striver also covers the version where both arrays are full (nums1 of size m, nums2 of size n, the result split across them). Mention it: the answers are swap-from-the-ends plus sorting, or the gap |
| Arrays | Check if array is sorted and rotated | Count circular drops — drops where a[i] > a[(i+1)%n]; answer drops ≤ 1 | O(n) | O(1) | Forgetting the wrap comparison: [2, 1, 3, 4] has one internal drop and would wrongly pass. | Start with the plain sorted check (a[i-1] ≤ a[i] for all i). Then extend it: try all n rotations against the sorted copy, which is O(n²). Then give the drop-count argument in one pass. Spell out the |
| Hashing | Longest Consecutive Sequence in an Array | Hash set, start only at run starts — x is a start iff x − 1 ∉ set; walk up from starts | O(n) average | O(n) | Walking from every element (no start check) → O(n²) on [1..n]. | The interviewer asks for O(n) specifically to rule out sorting. If they allow O(n log n), sorting is simpler and uses O(1) extra space — say both. |
| Hashing | Longest Subarray with Sum K | Prefix sum + first-index map — first[p] = earliest index; seed {0: −1}; len = i − first[p − k] | O(n) average | O(n) | Overwriting first[p] with later indices → shorter answers. | Ask immediately: "can values be negative?" All non-negative → sliding window, O(1) space (shown below as a variant). Negatives → prefix + map is required. |
| Hashing | Largest Subarray with Sum 0 | Equal prefix sums — first[p]; on repeat, len = i − first[p] | O(n) average | O(n) | Missing {0: −1} → misses prefixes that are 0 themselves. | |
| Hashing | Count Subarrays with Given Sum | Prefix sum + count map — ans += cnt[p − k]; then cnt[p] += 1; seed {0: 1} | O(n) average | O(n) | Seeding {0: 0} or nothing → misses subarrays from index 0. | The answer can reach n(n + 1)/2 ≈ 2·10⁸ here, still an int; for larger n use 64-bit. A sliding window doesn't work even for counting when negatives are present. |
| Hashing | Count Subarrays with Given XOR K | Prefix XOR + count map — ans += cnt[x ^ k]; then cnt[x] += 1; seed {0: 1} | O(n) average | O(n) | Looking up x − k out of habit. | XOR has no 'monotone' property at all, so there's no window alternative. Point out the two identities: x ^ x = 0 (prefix cancellation) and x ^ 0 = x (the seed). |
| Binary search | Search X in Sorted Array | Iterative binary search — closed interval [lo, hi]; drop the half that can't hold target | O(log n) | O(1) | while lo < hi with hi = n − 1 — misses the last candidate when lo == hi. | Warm-up question. They're checking that you write it bug-free first time: closed interval [lo, hi], while lo <= hi, mid = lo + (hi − lo) / 2, and lo = mid + 1 / hi = mid − 1. Say the invaria |
| Binary search | Lower Bound | Binary search with an answer variable — nums[mid] ≥ x → ans = mid, go left; else go right | O(log n) | O(1) | Returning −1 instead of n when nothing qualifies. | Lower bound is the single most reused primitive in this part: first occurrence, search insert, ceil, count occurrences, and the row-wise binary searches in 2D all reduce to it. Know the library versio |
| Binary search | Upper Bound | Binary search — nums[mid] > x → ans = mid, go left; else go right | O(log n) | O(1) | Confusing with lower bound (≥ vs >). | |
| Binary search | Search Insert Position | Lower bound — answer-variable binary search with ≥ | O(log n) | O(1) | Returning −1 when not found. | |
| Binary search | Floor and Ceil in Sorted Array | Two binary searches — floor: last nums[i] ≤ x · ceil: first nums[i] ≥ x | O(log n) | O(1) | Returning indices when values were asked (or vice versa) — clarify. | |
| Binary search | First and Last Occurrence | One search, two directions — on match record and continue left (first) or right (last) | O(log n) | O(1) | Finding one match and expanding linearly — O(n) worst case. | The trap: finding one occurrence then expanding left/right linearly is O(n) on [8, 8, 8, …, 8]. Interviewers ask for this exact input. |
| Binary search | Search in Rotated Sorted Array I | One pass: pick the sorted half — nums[lo] ≤ nums[mid] → left sorted; test range, else go right | O(log n) | O(1) | nums[lo] < nums[mid] (strict) — fails when lo == mid. | Draw the rotated array as two ascending ramps. Say: "one side of mid is always a single ramp — I can test membership there with two comparisons." Mention the alternative (find the pivot, then binary s |
| Binary search | Search in Rotated Sorted Array II | Rotated search with tie shrinking — if lo, mid, hi all equal: lo++, hi−−; else as in part I | O(log n) average, O(n) worst | O(1) | Shrinking only one end — still correct but easy to get wrong; shrinking both is symmetric and safe. | Expect the question "what's the worst case?" Answer: O(n), e.g. [1, 1, 1, …, 1, 2, 1, 1] — every step can only shrink by one. No algorithm beats Ω(n) here, since the lone different element could be |
| Binary search | Find Minimum in Rotated Sorted Array | Compare mid with hi — nums[mid] > nums[hi] → lo = mid + 1, else hi = mid; answer nums[lo] | O(log n) | O(1) | while lo <= hi with hi = mid — infinite loop. | |
| Binary search | Find Out How Many Times the Array Is Rotated | Index of minimum — nums[mid] > nums[hi] → lo = mid + 1, else hi = mid; return lo | O(log n) | O(1) | Returning the minimum's value instead of its index. | |
| Binary search | Single Element in a Sorted Array | Binary search on even indices — force mid even; pair intact → lo = mid + 2, else hi = mid | O(log n) | O(1) | Letting mid be odd and comparing with mid + 1 — pairs misalign. | Start with XOR (O(n)) to show you know the unsorted version, then point out that sortedness lets us binary-search on the *pairing pattern*, not on values. |
| Binary search | Count Occurrences in a Sorted Array | Upper bound − lower bound — two binary searches | O(log n) | O(1) | Finding one occurrence then counting outward — O(n). | |
| Binary search | Find Square Root of a Number | Binary search on the answer — mid² ≤ n → ans = mid, lo = mid + 1; else hi = mid − 1 | O(log n) | O(1) | 32-bit mid * mid. | This is the gateway to "binary search on the answer": the search space is the *range of possible answers*, not array indices. Say: "answers 0..n, predicate mid² ≤ n is monotone, I want the largest tru |
| Binary search | Find Nth Root of a Number | Binary search with capped power — pow(mid, n) returns 0/1/2 for < / = / > m | O(n log m) | O(1) | Library pow + cast — rounding errors. | |
| Binary search | Find the Smallest Divisor | Binary search on d — check(d) = Σ ceil(x/d) ≤ threshold; first true in [1, max] | O(n log max) | O(1) | Using floor division instead of ceiling. | This is the template every "minimum X such that a greedy check passes" problem uses (Koko, bouquets, ship packages, split array). Name the three pieces: range [1, max], check(d) in O(n), **d |
| Binary search | Koko Eating Bananas | Binary search on speed — hours(k) ≤ h → ans = k, go left; else go right | O(n log max) | O(1) | 32-bit hour counter. | The flagship BS-on-answer problem at Google-style interviews. State why the upper bound is max(piles): at that speed every pile takes one hour, and going faster can't help. Use 64-bit for the hour s |
| Binary search | Minimum Days to Make M Bouquets | Binary search on day — impossible if m·k > n; else first d in [min, max] with bouquets(d) ≥ m | O(n log(max − min)) | O(1) | Not resetting run after forming a bouquet (flowers reused). | |
| Binary search | Capacity to Ship Packages Within D Days | Binary search on capacity — days_needed(cap) ≤ days → go left; greedy check | O(n log Σw) | O(1) | Lower bound 1 instead of max(weights) — the check then loops forever or miscounts (a package heavier than cap never fits). | This is the "split a sequence into ≤ k contiguous parts minimising the maximum part" pattern — the same code solves Book Allocation, Painter's Partition and Split Array Largest Sum (all later in this |
| Binary search | Kth Missing Positive Number | Binary search on missing count — missing(i) = arr[i] − i − 1; first i with missing ≥ k; return lo + k | O(log n) | O(1) | Returning arr[lo] + … — lo may be n (out of range). | Derive lo + k aloud: after the loop, hi = lo − 1 is the last index with fewer than k missing. Answer = arr[hi] + (k − missing(hi)) = arr[hi] + k − (arr[hi] − hi − 1) = hi + 1 + k = `lo + k |
| Binary search | Painter's Partition | Binary search on max load — painters_needed(cap) ≤ k → go left | O(n log Σ) | O(1) | 32-bit sums. | When asked, say immediately: "This is split-array-largest-sum." If k > n, extra painters idle — the answer is max(boards), which the binary search returns naturally since the greedy uses ≤ n paint |
| Binary search | Aggressive Cows | Binary search on distance — sort; can_place(d) → ans = d, go right | O(n log n + n log range) | O(1) extra | Forgetting to sort. | The canonical "max of min" problem. Contrast it with ship packages ("min of max"): there you go left on true; here you go right on true. Explain why greedy placement is optimal: putting the first |
| Binary search | Book Allocation Problem | Binary search on max pages — m > n → −1; first cap in [max, Σ] with students(cap) ≤ m | O(n log Σ) | O(1) | Missing the m > n guard. | Why does "each student gets ≥ 1 book" not complicate the check? If the greedy uses fewer than m students at some cap, you can always split a multi-book student to use more (when m ≤ n) without rai |
| Binary search | Find Peak Element | Binary search on slope — nums[mid] < nums[mid+1] → lo = mid + 1 else hi = mid | O(log n) | O(1) | Using while lo <= hi with hi = mid — infinite loop. | This is the go-to example that binary search doesn't need sorted input — it needs a predicate that tells you which half is guaranteed to contain an answer. Say that sentence. |
| Binary search | Median of 2 Sorted Arrays | Binary search the partition — search c1 in smaller array; valid when l1 ≤ r2 and l2 ≤ r1 | O(log min(n₁, n₂)) | O(1) | Searching the larger array → c2 goes negative. | Hardest standard binary search question. Present it in three steps: (1) merge → O(n) baseline, (2) "the median is fixed by a cut that puts half the elements on the left", (3) search that cut in the sm |
| Binary search | Kth Element of 2 Sorted Arrays | Binary search the partition — c1 ∈ [max(0, k − n₂), min(k, n₁)]; valid cut → max(l1, l2) | O(log min(n₁, n₂)) | O(1) | Range [0, n1] without the k bounds → c2 out of range. | |
| Binary search | Minimize Max Distance to Gas Station | Binary search on the answer (reals) — need(d) = Σ (⌈g/d⌉ − 1) ≤ k → hi = d else lo = d; 100 iterations | O(n · 100) | O(1) | Using g / d stations instead of ⌈g/d⌉ − 1. | Show the progression: O(k·n) brute → O(k log n) heap (always split the currently largest *piece*) → O(n log(range/ε)) binary search. Name why the heap stores gap / (placed + 1): placing stations eve |
| Binary search | Split Array — Largest Sum | Binary search on largest sum — parts(cap) ≤ k → go left | O(n log Σ) | O(1) | Lower bound 0 / 1 instead of max(nums). | Mention the DP alternative to show breadth: dp[i][j] = best for the first i elements in j parts, O(n² k). Binary search wins at O(n log Σ). |
| Binary search | Find Row with Maximum 1's | Lower bound per row — ones = m − first index of 1 | O(n log m) | O(1) | ≥ on tie → returns the last tied row. | |
| Binary search | Search in a 2D Matrix | Flattened binary search — idx → (idx / m, idx % m) | O(log(n · m)) | O(1) | mid / n instead of mid / m (divide by column count). | |
| Binary search | Search in 2D Matrix II | Staircase from top-right — v > target → col − 1; v < target → row + 1 | O(n + m) | O(1) | Starting at top-left — both moves increase value. | Interviewers often expect you to first try "binary search each row" (O(n log m)) and then find the staircase. Explain why top-left or bottom-right corners don't work: from there both moves go the same |
| Binary search | Find Peak Element II | Binary search on columns — r = argmax column mid; compare with left/right | O(n log m) | O(1) | Picking any cell in column mid instead of the column max — vertical neighbours may be larger. | Build on 1D peak: "if I collapse each column to its maximum, I get a 1D array; the 1D slope argument then applies, and the column max already beats its vertical neighbours." |
| Binary search | Matrix Median | Binary search on value — first x with Σ upper_bound(row, x) > nm/2 | O(n log m · log(max − min)) | O(1) | lower_bound instead of upper_bound (counts < x, not ≤ x). | "Binary search on value + count" is the trick behind k-th smallest in a sorted matrix (LC 378), k-th smallest pair distance (LC 719) and median of k arrays. The median is the (nm/2 + 1)-th smallest. |
| Strings basic medium | Remove Outermost Parentheses | Depth counter — drop ( at depth 0 and ) back to depth 0 | O(n) | O(n) output | Checking depth after incrementing on ( — drops nothing, or the wrong chars. | Easy warm-up that checks whether you reach for a stack by reflex. With one bracket type, the stack only ever holds (, so its size is all that matters — an int. Mention that a stack is the general to |
| Strings basic medium | Maximum Nesting Depth of the Parentheses | Running depth — depth++ on ( and update max; depth-- on ) | O(n) | O(1) | Updating the max after ) — you record a value one too low. | Asked as a 5-minute opener. Do it in one pass, O(1) space, and update the max right after incrementing (the max happens on an opening paren). |
| Strings basic medium | Roman to Integer | Subtract if smaller than the next — v < next → total −= v else total += v | O(n) | O(1) | Reading s[i + 1] without the bounds check. | Easy, but they watch whether you hard-code six special cases or find the general rule. State the rule: a symbol is subtracted iff a larger symbol follows it. Be ready for the reverse (LC 12, integer t |
| Strings basic medium | String to Integer (atoi) | Iterative with pre-multiply overflow guard — if res > (MAX − d) / 10 → clamp | O(n) | O(1) | res * 10 + d then checking — the overflow already happened (UB in C++). | A favourite because the spec is the test: interviewers want you to list the cases (spaces, sign, leading zeros, junk, empty, overflow both ways, "+-1") *before* coding. In C++/Java show the overflow |
| Strings basic medium | Count Substrings with Exactly K Distinct Characters | atMost(k) − atMost(k − 1) — window counts substrings with ≤ k distinct; subtract | O(n) | O(26) | Trying to maintain an "exactly k" window directly. | The point is the subtraction trick. A direct window for "exactly k" fails: when the window has exactly k, you can't decide whether to grow or shrink. Explain why "at most" works (shrinking never break |
| Strings basic medium | Longest Palindromic Substring | Expand around centre — 2n − 1 centres; widen while s[l] == s[r] | O(n²) | O(1) | Only odd centres — misses bb. | Top-10 string question. Expected path: brute O(n³) → DP O(n²) time and space → expand around centre O(n²) time, O(1) space. Mention Manacher's O(n) by name and that it isn't expected at L3/L4. Forgett |
| Strings basic medium | Sum of Beauty of All Substrings | Incremental counts per start — fix i; extend j, cnt[s[j]]++, add max − min of non-zero counts | O(26 · n²) | O(26) | Including zero counts in the min — makes min 0 everywhere. | The constraint (n ≤ 500) tells you O(n²) with a small constant is intended. The point is recognising that recounting each substring (O(n³)) is wasteful — extending the end by one changes exactly one c |
| Recursion | Pow(x, n) | Iterative binary exponentiation — walk the bits of n; square x each step, multiply when the bit is set | O(log n) | O(1) | pow(x, n/2) * pow(x, n/2) — two recursive calls make it O(n). | The classic first recursion question that's really about complexity. Expected: O(n) loop → O(log n) recursion → iterative bit version. The trap they wait for is n = −2³¹: -n overflows int, so conv |
| Recursion | Generate Parentheses | Backtracking on open/close counts — '(' if open < n; ')' if close < open | O(4ⁿ / √n) | O(n) recursion + output | Allowing ) when close == open — produces invalid prefixes. | Standard backtracking check. Start with the brute (generate 2²ⁿ, validate) to show you see the search space, then prune. Be ready to state the output size: Catalan Cₙ = (2n choose n)/(n + 1) ≈ 4ⁿ / (n |
| Recursion | Power Set | Pick / not-pick recursion — at index i: recurse without nums[i], then with it | O(n · 2ⁿ) | O(n) recursion | Appending cur itself instead of a copy — every entry ends up identical (empty). | The template every subset/combination problem is built on — interviewers expect both the recursive and the bitmask version. State the cost: 2ⁿ subsets × O(n) to copy each = O(n · 2ⁿ), which is optimal |
| Recursion | Count Good Numbers | Fast modular power — pow(5, ⌈n/2⌉) · pow(4, ⌊n/2⌋) mod p | O(log n) | O(1) | Swapping ⌈n/2⌉ and ⌊n/2⌋ (index 0 is even). | Two steps: (1) the combinatorics — multiply choices per position; (2) the constraint 10¹⁵ rules out a loop, so modular fast power. Watch the 64-bit products: (a · b) % MOD with both < 10⁹ + 7 fits i |
| Recursion | Reverse a Stack | Recursion with insert-at-bottom — pop top, reverse rest, insert top at bottom | O(n²) | O(n) call stack | Pushing the popped top back on top instead of at the bottom. | Tests whether you can design two mutually-layered recursions with clean contracts: insertAtBottom(st, x) places x under everything, and reverse(st) assumes it works on the smaller stack. Expect th |
| Recursion | Check if There Exists a Subsequence with Sum K | 1D subset-sum DP — can[s] | = can[s − x], s from k down to x | O(n · k) | O(k) | Iterating sums upward in the 1D DP — reuses an item (unbounded knapsack). | This is the "return as soon as found" variant of the subsequence template: if (take) return true; return skip. Then the interviewer asks for better than 2ⁿ — show memoisation and the 1D DP (iterate |
| Recursion | Count All Subsequences with Sum K | 1D counting DP — ways[s] += ways[s − x], s from k down to x | O(n · k) | O(k) | Returning 1 as soon as rem == 0 before i == n — wrong once zeros exist. | This finishes the three-variant ladder (print all → return any → count). The structural point: printing needs side effects, finding needs short-circuit boolean returns, counting needs summed integer r |
| Recursion | Generate Binary Strings Without Consecutive 1s | Backtracking with last-char check — always try 0; try 1 only if the previous char is 0 | O(n · Fib(n)) | O(n) | Checking the *next* char instead of the previous. | Simple generation question that checks pruning at the branch (don't generate 11 then filter) and that you can state the output size: strings ending in 0 extend any string, strings ending in 1 extend |
| Recursion | Combination Sum | Loop-based backtracking (sorted, with break) — for j in [start, n): take c[j], recurse from j | O(2^(t/m) · t) | O(t/m) | Recursing with j + 1 — forbids reuse. | The first of the Combination Sum family; interviewers move straight to II (duplicates, use once) and III (fixed size). Explain the difference in one line each: I recurses on j, II recurses on `j + 1 |
| Recursion | Combination Sum II | Loop backtracking with sibling skip — sort; skip c[j] == c[j−1] when j > start; recurse j + 1 | O(2ⁿ · n) worst | O(n) | j > 0 instead of j > start — drops [1, 1, 6]. | The duplicate-skip rule j > start && c[j] == c[j−1] is the whole question; be ready to explain why j > start (not j > 0): the first equal value at a level is allowed, so [1, 1, 6] still appears |
| Recursion | Subsets I (Subset Sums) | Recursion with running sum — go(i, s): skip → go(i+1, s); take → go(i+1, s + a[i]) | O(2ⁿ) | O(n) stack + output | Dropping the empty subset's 0. | Warm-up: recognise that you don't need the subsets themselves, only the accumulator — a cheaper state. It's also the building block for meet-in-the-middle (split in halves, enumerate each half's sums, |
| Recursion | Subsets II | Loop backtracking, record every node — record cur; for j ≥ i: skip equal siblings, push, recurse j + 1 | O(n · 2ⁿ) | O(n) | Forgetting to sort. | Pairs with Combination Sum II — same skip rule, but no target, so every node is recorded. If you present the pick/not-pick version, the dedupe there is: after deciding *not* to take a[i], skip all f |
| Recursion | Combination Sum III | Backtracking in increasing order — for d in start..9: if d > rem break; push; recurse d + 1 | O(C(9, k) · k) | O(k) | Not stopping at size k — recursion keeps adding digits. | A quick one — the value is in stating the tight bound (C(9, k)) and adding two prunes: d > rem → break and "not enough digits left". The bitmask version over 2⁹ = 512 masks is equally acceptable and |
| Recursion | Letter Combinations of a Phone Number | Backtracking per digit — go(i): for ch in map[digits[i]]: push, go(i + 1), pop | O(4ⁿ · n) | O(n) | Returning [""] for empty input. | Easy to code; the signals are the empty-input edge case, a fixed mapping array instead of a hash map, and stating the complexity with the 4-letter digits (7, 9) as worst case. The iterative BFS-style |
| Recursion | Palindrome Partitioning | Backtracking + palindrome table — isPal[i][j] DP, then the same backtracking with O(1) checks | O(n · 2ⁿ) | O(n²) | Filling isPal with i ascending — pal[i+1][j−1] not ready yet. | The "partition" family template: the recursion variable is the start of the remaining suffix, the loop chooses where the next piece ends. Worst case is "aaaa…" with 2ⁿ⁻¹ partitions, so O(n · 2ⁿ). Fo |
| Recursion | Word Search | DFS marking the board in place — board[r][c] = '#' during the visit, restore after | O(m·n·3^L) | O(L) recursion | Not restoring the cell — later starts see # and fail. | Expect: in-place visited marking (no extra matrix), short-circuit on the first true, and a complexity of O(m · n · 3^L) (after the first step each cell has ≤ 3 unvisited neighbours). Bonus prunes: if |
| Recursion | N-Queens | Row recursion with column/diagonal sets — cols[c], diag[r − c + n − 1], anti[r + c] | O(n!) | O(n) | Negative index for r − c — offset by n − 1. | The canonical backtracking showcase. Start from "one queen per row" (which collapses n² choose n to n! orderings), then the O(1) diagonal sets via r − c + n − 1 and r + c indices. Solution counts |
| Recursion | Rat in a Maze | DFS in D, L, R, U order — direction arrays in alphabetical order → sorted output | O(3^(n²) · n²) | O(n²) | Not checking the start cell. | Same skeleton as Word Search but collecting every path instead of stopping at the first. Points to mention: check the start cell, use direction arrays dr/dc/ch in DLRU order to get sorted output, an |
| Recursion | M-Coloring Problem | Backtracking vertex by vertex — for colour c in 1..m: if safe(v, c) → assign, recurse, undo | O(mⁿ) worst | O(n + E) | Checking all vertices for conflicts instead of only neighbours. | Template backtracking: state = colours of vertices < v, choice = colour of v, constraint = neighbours. Mention: m ≥ max degree + 1 is always enough (greedy), m = 2 is just bipartite checking (BFS, pol |
| Recursion | Sudoku Solver | Backtracking with constraint tables — row/col/box used-digit tables; recurse over the list of empty cells | O(9^E) | O(E + 243) | Box index r/3 + c/3 instead of (r/3)·3 + c/3. | They expect the clean backtracking with a boolean return (true once solved, so the filled board is kept) and the box index formula. Strong answers add constraint tables instead of rescanning, and me |
| Recursion | Expression Add Operators | Backtracking with value and last term — go(i, value, last): pick operand num[i..j], try +, −, * | O(n · 4ⁿ) | O(n) | Evaluating left to right — 2+3*2 would give 10. | The hard part is precedence: you can't evaluate left to right once * appears. Explain the last operand trick before coding. Use 64-bit values (10-digit operands overflow int), and note the cost: 4 |
| Recursion | Sort a stack using recursion | Pure recursion (sort + insertSorted) — pop x, sort rest, insert x in place | O(n²) | O(n) call stack | Using a loop over the stack, which the problem forbids. | Frame it with induction. Hypothesis: sort(st) sorts the stack. Induction step: pop x, sort the rest, then insert x in its place. Base case: an empty stack. insertSorted uses the same kind of |
| Linked list | Traversal in Linked List | Iterative walk — cur = head; while cur: visit; cur = cur.next | O(n) | O(1) extra | Moving head and losing the list. | Warm-up that checks you know the loop condition: while cur visits every node; while cur.next stops on the tail and is what you use when you need the last node itself. |
| Linked list | Deletion of the Head of LL | Advance the head — tmp = head; head = head.next; free tmp | O(1) | O(1) | Dereferencing head.next without the null check. | O(1) — the reason linked lists beat arrays for front deletion (array shift is O(n)). Mention returning the new head; void functions can't change the caller's pointer in C++ unless passed by reference. |
| Linked list | Deletion of the Tail of LL | Walk to the second-last node — while cur.next.next: cur = cur.next; cur.next = null | O(n) | O(1) | Walking to the tail itself — then you can't unlink it. | Tests the "stop one node early" habit — to remove a node in a singly list you need its predecessor. O(n) because there is no back pointer; a DLL with a tail pointer makes it O(1). |
| Linked list | Deletion of the Kth Element of LL | Dummy node — dummy → head; step k − 1 from dummy; bypass | O(k) | O(1) | Walking to node k instead of k − 1. | The dummy-node trick is the takeaway: point a sentinel at head, walk k − 1 steps from the sentinel, bypass, return dummy.next. Head deletion stops being a special case. |
| Linked list | Delete the Element with Value X | Dummy + search predecessor — prev from dummy until prev.next.val == x; bypass | O(n) | O(1) | Comparing cur.val with no predecessor kept. | Ask: first occurrence or all? All occurrences is LC 203 — the same loop without break, and you must not advance prev after a deletion. |
| Linked list | Insertion at the Head of LL | New node points at old head — node(x).next = head; return node | O(1) | O(1) | head = node; node.next = head — order reversed creates a self-loop. | O(1) — this is how a linked-list stack pushes. Set the new node's next before moving the head. |
| Linked list | Insertion at the Tail of LL | Walk to the tail — while cur.next: advance; cur.next = node(x) | O(n) | O(1) | while cur overshoots to null; cur.next then crashes. | Note that you need while cur.next here (stop on the tail) — contrast with traversal's while cur. Mention that queues keep a tail pointer to make this O(1). |
| Linked list | Insertion at the Kth Position of LL | Dummy + splice — step k − 1 from dummy; node.next = prev.next; prev.next = node | O(k) | O(1) | prev.next = node; node.next = prev.next — node points to itself. | The splice order matters: link the new node to the rest before redirecting the predecessor, or you lose the tail. |
| Linked list | Insertion Before the Value X in LL | Dummy + search predecessor — prev.next.val == x → splice | O(n) | O(1) | Not breaking after inserting — loops forever if val == x. | Same predecessor pattern as Delete Value X — in a singly list you can only insert after a node you hold, so "before X" means "after X's predecessor". |
| Linked list | Find the Length of the Linked List | Iterative count — cnt++ per node | O(n) | O(1) | Starting the count at 1 and double counting on empty lists. | Trivial — but know both versions: iterative O(1) space, recursive 1 + len(next) O(n) stack (overflows for 10⁵ nodes in Python). |
| Linked list | Search in Linked List | Linear scan — return true on match | O(n) | O(1) | Returning false inside the loop on the first mismatch. | Follow-up you may get: "can you binary search a sorted linked list?" — no, finding the middle costs O(n), so the total is O(n log n) without benefit. Skip lists add express lanes to make it O(log n). |
| Linked list | Convert Array to DLL | Tail pointer — node(prev = tail); tail.next = node; tail = node | O(n) | O(n) output | Setting tail.next but not node.prev — forward traversal works, backward breaks. | Say the invariant out loud: after each step, tail.next == null and every node.next.prev == node. Interviewers watch for the forgotten prev. |
| Linked list | Delete Head of DLL | Advance + clear prev — head = head.next; head.prev = null | O(1) | O(1) | Leaving newHead.prev pointing at the deleted node. | The dangling prev is the bug the interviewer is looking for: the old head is gone but newHead.prev still points at it. |
| Linked list | Delete Tail of DLL | Walk to tail, cut via prev — tail.prev.next = null | O(n) | O(1) | Single node: tail.prev is null → crash. Handle it first. | With a stored tail pointer this is O(1) — that's why a DLL makes a deque: both ends pop in O(1), which a singly list can't do at the tail. |
| Linked list | Delete Kth Element of DLL | Locate + unlink — fix prev.next and next.prev, each if present | O(k) | O(1) | Fixing p.next but not n.prev. | Narrate the 4-case table — it's the template for every DLL unlink (LRU cache remove(node) included). A sentinel head + tail collapses all four to the middle case. |
| Linked list | Removing Given Node in DLL | Rewire neighbours — prev.next = next; next.prev = prev (if next) | O(1) | O(1) | Clearing node.next before reading it. | Contrast with LC 237 (singly): there you must copy the next value and delete the next node instead, and it fails for the tail. This O(1) unlink is why LRU caches use a DLL. |
| Linked list | Insert Node Before Head in DLL | Link both ways — node.next = head; head.prev = node | O(1) | O(1) | Forgetting head.prev = node. | O(1). Mention the null check on the old head — the singly version doesn't need it. |
| Linked list | Insert Node Before Tail in DLL | Walk to tail + insert before — node(next = t, prev = t.prev); fix both neighbours | O(n) | O(1) | Setting t.prev = node before reading t.prev for the new node. | Write a helper insertBefore(t, x) once and reuse it for the next three problems — interviewers like seeing the shared primitive. |
| Linked list | Insert Node Before Kth Node in DLL | Locate k-th + insert before — walk k − 1; node(next = t, prev = t.prev) | O(k) | O(1) | Walking k steps instead of k − 1. | Same helper as Insert Before Tail — only the locate step changes. |
| Linked list | Insert Before Given Node in DLL | Splice between prev and node — 4 link updates | O(1) | O(1) | Updating node.prev first, then reading it as the predecessor. | The guarantee "not the head" is what makes this void: inserting before the head would change the head, which the caller couldn't see. |
| Linked list | Reverse a Doubly Linked List | Swap prev/next in place — swap; advance via cur.prev; last visited = head | O(n) | O(1) | Advancing with cur.next after the swap — goes backwards and loops. | Lead with the brute force (stack of values, rewrite) to show you can, then do the O(1)-space swap. Name the trick: "after swapping, prev is my forward pointer." |
| Linked list | Add Two Numbers in LL | Simultaneous walk with carry — while l1 or l2 or carry: s = …; tail.next = node(s % 10) | O(max(m, n)) | O(1) extra (output aside) | Dropping the final carry (999 + 1). | Converting to integers overflows (100 digits) — say so and reject it. The single loop while l1 or l2 or carry handles unequal lengths and the final carry in one place. |
| Linked list | Segregate Odd and Even Nodes in LL | Weave two chains — odd/even pointers leapfrog; odd.next = evenHead | O(n) | O(1) | Not saving evenHead before weaving. | Clarify positions vs values first (Striver's version and LC 328 are positional). Loop condition while even and even.next covers both odd and even lengths. |
| Linked list | Sort a LL of 0's, 1's and 2's | Three chains — append to zero/one/two dummies; join; cut tail | O(n) | O(1) | zeroTail.next = oneHead.next when there are no ones → twos lost. | Counting (two passes, rewrite values) is acceptable and simple — mention it, then do the one-pass relink. The tricky line is the join: zt.next = oneH.next or twoH.next. |
| Linked list | Remove Nth Node from the Back of the LL | One pass, gap of n — fast n ahead; move both until fast.next is null | O(n) | O(1) | Starting at head instead of a dummy → can't remove the head. | Give the two-pass version (length, then len − n steps) first, then the one-pass gap trick — the follow-up is always "can you do it in one pass?" |
| Linked list | Reverse a LL | Iterative three pointers — nxt = cur.next; cur.next = prev; prev, cur = cur, nxt | O(n) | O(1) | Overwriting cur.next before saving it. | The single most reused linked-list primitive (palindrome, reorder, k-group, add-one). Be ready to write both versions cold and state the recursive one's O(n) stack. |
| Linked list | Add One to a Number Represented by LL | Rightmost non-9 — find last digit ≠ 9; ++ it; zero the rest | O(n) | O(1) | Forgetting the new head on overflow. | Three answers in increasing elegance: reverse twice (O(1) space), recursion (O(n) stack), and the "last non-9" trick — find the rightmost digit ≠ 9, increment it and zero everything after. |
| Linked list | Find Middle of Linked List | Tortoise and hare — slow += 1, fast += 2 while fast and fast.next | O(n) | O(1) | Mixing up loop conditions → wrong middle for even lengths. | Know which loop condition gives which middle — merge sort on a list needs the first middle (so the left half is non-empty and smaller), this problem needs the second. |
| Linked list | Delete the Middle Node in LL | Fast with a head start — slow = head, fast = head.next.next; bypass slow.next | O(n) | O(1) | Landing on the middle itself — can't delete it without its predecessor. | Explain why the head start works: shifting fast two steps ahead makes slow lag one node behind where it would be — the predecessor. |
| Linked list | Check if LL is Palindrome or Not | Reverse second half — first middle → reverse after it → compare → restore | O(n) | O(1) | Using the second middle — odd lengths then compare the middle against nothing, fine, but even lengths misalign if you also iterate the first half fully. | Start with the stack/array version (O(n) space), then the O(1) version. Mention restoring the list — modifying input silently is a code-review red flag. |
| Linked list | Find the Intersection Point of Y LL | Pointer switching — p = p.next or headB; q = q.next or headA; until p is q | O(m + n) | O(1) | Comparing values instead of node identity. | Equal values don't mean intersection — it's node identity. Walk through all three solutions: hash set, length difference, pointer switching. The switching one is the expected final answer. |
| Linked list | Detect a Loop in LL | Floyd tortoise and hare — slow 1, fast 2; meet → cycle | O(n) | O(1) | Checking slow == fast before moving (they start equal). | Prove it: once both are in the cycle, the distance from fast to slow (going forward) drops by exactly 1 per step, so it hits 0 — fast can't jump over slow. |
| Linked list | Find the Starting Point in LL | Floyd + reset to head — meet; p = head; step both by 1 until equal | O(n) | O(1) | Resetting both pointers. | The derivation is what's graded. L = distance head→start, d = start→meeting, C = cycle length. Slow walked L + d, fast walked 2(L + d) = L + d + kC ⇒ L + d = kC ⇒ L = kC − d. From the meeting point, w |
| Linked list | Length of Loop in LL | Floyd + one lap — meet; walk until back at meeting point | O(n) | O(1) | Starting count at 0 with cur = slow and loop while cur is not slow — never enters. | Same Floyd phase 1, different phase 2. Alternative: hash map node → index; on revisit, length = current index − stored index. |
| Linked list | Reverse LL in Group of Given Size K | Iterative with k-th node finder — kth = walk k−1; detach; reverse; reconnect | O(n) | O(1) | Reversing the short leftover group. | This is all bookkeeping — name the four pointers aloud (group start, k-th node, next group, prev tail) and draw one group before coding. A dummy head removes the "first group" special case. |
| Linked list | Rotate a LL | Ring and cut — tail.next = head; walk n − k%n − 1; cut | O(n) | O(1) | Not reducing k mod n → TLE. | k can be 2·10⁹ — saying "k mod n" up front is the signal. The ring trick avoids a separate re-attach step. |
| Linked list | Merge Two Sorted Lists | Dummy + tail splice — attach smaller; advance; append leftover | O(n+m) | O(1) | Looping until both are null instead of appending the remainder. | The building block for Sort List, Merge K Lists, and Flattening. Use <= to keep it stable. |
| Linked list | Flattening of LL | Recursive merge from the right — head.next = flatten(head.next); merge(head, head.next) | O(N · k) | O(k) stack | Leaving stale next pointers in the result. | Name it immediately: "this is merge k sorted lists along child". Then pick recursion (O(N·k)) or a heap (O(N log k)); mention the trade-off. |
| Linked list | Sort LL | Top-down merge sort — split at first middle; sort; merge | O(n log n) | O(log n) stack | Second middle split → infinite recursion on 2 nodes. | Why not quicksort? Bad pivots on linked lists and no cheap random pivot. Why first middle? With the second middle, a 2-node list splits as 2 + 0 and recursion never terminates. Bottom-up merge sort gi |
| Linked list | Clone a LL with Random and Next Pointer | Interleave, wire random, unweave — A→A'→B→B'; A'.random = A.random.next; split | O(n) | O(1) extra | Setting random in the same pass as inserting copies — later copies don't exist yet. | Hash map first (clear and correct), then interleaving for O(1) extra. Emphasize restoring the original in pass 3 — a common bug the grader checks. |
| Linked list | Delete All Occurrences of a Key in DLL | In-place unlink — match → link prev ⇄ next; move head if needed | O(n) | O(1) | Not updating nxt.prev. | Save nxt before unlinking. Mention fixing nxt.prev — forgetting it silently corrupts backward traversal, which a forward-only check won't catch. |
| Linked list | Remove Duplicates from Sorted DLL | Skip equal run — nxt = first node with different value; relink | O(n) | O(1) | Forgetting nxt.prev = cur. | One pass, two pointers. Same as LC 83 plus the prev fix-up. |
| Linked list | Find Pairs with Given Sum in DLL | Two pointers from both ends — sum < t → left++; > t → right--; = → record, move both | O(n) | O(1) | Loop guard left is not right alone — after moving both on a match they can cross and continue. | Point out that prev is what makes the O(1)-space version possible; on a singly list you'd need a hash set or reverse a half. Stop condition: left is not right and right.next is not left (or compar |
| Bit manipulation | Check if the i-th Bit is Set | Left-shift mask — n & (1 << k) != 0 | O(1) | O(1) | Missing parentheses: n & 1 << k != 0. | Warm-up that checks you know both shift directions and operator precedence. In C/C++/Java n & 1 << k == 0 parses as n & ((1 << k) == 0) — always parenthesise. |
| Bit manipulation | Check if a Number is Odd | AND with 1 — n & 1 | O(1) | O(1) | n % 2 == 1 for negatives in C++/Java. | Trivial on its own — the follow-up is why n % 2 == 1 is wrong for negatives in C++/Java (-3 % 2 == -1) while n & 1 is correct. |
| Bit manipulation | Check if a Number is Power of 2 | n & (n − 1) — one set bit ⇔ clearing it gives 0 | O(1) | O(1) | Forgetting n > 0. | The expected answer is the one-liner; what's being tested is the n > 0 guard (0 and INT_MIN both satisfy n & (n−1) == 0 style tricks incorrectly) and that you can explain *why* n & (n − 1) clear |
| Bit manipulation | Count the Number of Set Bits | Brian Kernighan — n &= n − 1 until 0 | O(popcount) | O(1) | Using arithmetic >> on negative numbers → infinite loop (sign bit keeps refilling). | Give the shift loop, then Kernighan as the improvement, and mention the built-ins (__builtin_popcount, Integer.bitCount, int.bit_count()). Interviewers like hearing the iteration count is the nu |
| Bit manipulation | Set the Rightmost Unset Bit | n — (n + 1) | +1 carries through trailing 1s into the lowest 0 | O(1) | O(1) | Confusing it with n & (n − 1) (which clears the lowest set bit). | Part of a family of one-liners — know all four: clear lowest set n & (n−1), isolate lowest set n & −n, set lowest unset n | (n+1), isolate lowest unset ~n & (n+1). |
| Bit manipulation | Swap Two Numbers | XOR swap — a ^= b; b ^= a; a ^= b | O(1) | O(1) | a ^= b ^= a ^= b in one expression — unsequenced modification, undefined behaviour in C/C++. | Show you know the XOR identities, then say you wouldn't use this in production: std::swap / tuple assignment is clearer, and XOR swap zeroes the value if both references alias the same memory. |
| Bit manipulation | Minimum Bit Flips to Convert Number | XOR + Kernighan — popcount(start ^ goal) | O(popcount) | O(1) | Stopping the scan loop when only one number reaches 0. | Same as Hamming distance (LC 461). Say "XOR gives the diff mask, popcount counts it" and you're done in two lines. |
| Bit manipulation | Single Number I | XOR everything — pairs cancel | O(n) | O(1) | Summing instead of XOR (2·Σdistinct − Σ works but needs a set → O(n) space). | Walk up the ladder: hash map count (O(n) space) → sort and compare pairs (O(n log n)) → XOR. Explain *why* XOR works using its three identities. |
| Bit manipulation | Single Number II | ones / twos state machine — ones = (ones ^ x) & ~twos; twos = (twos ^ x) & ~ones | O(n) | O(1) | Using XOR alone — triples don't cancel. | Expect to explain the bit-count approach first — it generalises to "appears k times". The ones/twos version is the follow-up; derive it as a two-bit counter per bit position rather than reciting i |
| Bit manipulation | Single Number III | XOR + split on lowest differing bit — x = a ^ b; low = x & −x; XOR each half | O(n) | O(1) | -x on INT_MIN in C++ signed int — undefined behaviour; use unsigned. | The hard part is justifying the split. Say: "a ^ b has a 1 where a and b differ; pick any such bit. Duplicates share every bit so each pair goes to the same side." Then mention x & −x overflows fo |
| Bit manipulation | Divide Two Integers | Shift and subtract — subtract the biggest divisor·2ᵏ that fits | O(log² n) | O(1) | abs(INT_MIN) in 32-bit — still negative. | Ask about overflow up front (the only case is INT_MIN / −1). Work on absolute values in 64-bit, compute the sign with XOR of signs, and explain the doubling loop as binary long division. |
| Bit manipulation | Power Set (Bit Manipulation) | Bitmask enumeration — for mask in 0…2ⁿ−1, include nums[i] if bit i set | O(n·2ⁿ) | O(n·2ⁿ) output | 1 << n for n ≥ 31 in int. | Contrast with the recursive pick/not-pick version from [Recursion](../18-recursion/README.md). The bitmask version is iterative and has no stack depth; both are O(n·2ⁿ). Mention that n ≤ 20 is the usu |
| Bit manipulation | XOR of Numbers in a Given Range | Prefix XOR f(R) ^ f(L − 1) — f(n) by n mod 4 | O(1) | O(1) | Using f(R) ^ f(L) (drops L). | Derive the pattern rather than reciting it: every block 4k, 4k+1, 4k+2, 4k+3 XORs to 0 (high bits cancel in pairs, low bits 00^01^10^11 = 0). So only the partial last block matters. |
| Greedy algorithms | Assign Cookies | Sort + two pointers — advance cookie always, child when fed | O(n log n + m log m) | O(1) extra | Advancing the child pointer when the cookie is too small (should discard the cookie). | The opener for greedy: the interviewer wants the sort and a one-line exchange argument — if an optimal solution feeds the least greedy child a bigger cookie, swapping in the smallest feasible cook |
| Greedy algorithms | Lemonade Change | Counters with greedy change — track #5 and #10; for 20 use 10+5 first | O(n) | O(1) | Giving 5 + 5 + 5 for 20 before trying 10 + 5. | A simulation question with one real decision. State why 10 + 5 is the right change for 20: it preserves $5s, which every change-giving case needs. |
| Greedy algorithms | Fractional Knapsack | Sort by ratio, fill greedily — best v/w first; last item fractional | O(n log n) | O(n) | Sorting by value or by weight instead of by ratio. | The classic contrast with 0/1 knapsack. Expect: "why is greedy optimal here but not there?" Answer: any unit of capacity spent on a lower ratio can be swapped for a unit of a higher ratio (exchange), |
| Greedy algorithms | Jump Game I | Greedy farthest reach — maxReach = max(maxReach, i + nums[i]) | O(n) | O(1) | Returning false as soon as you see a 0 — it may be jumpable. | Show the DP/recursion first only if asked; the expected answer is the O(n) reach scan with the argument "reachable indices always form a prefix". |
| Greedy algorithms | Shortest Job First | Sort + running time — sort; wait += elapsed; elapsed += b | O(n log n) | O(1) extra | Adding the job's own burst to its waiting time (that's turnaround time). | Expect the scheduling proof: total wait = Σ (n − 1 − k) · b₍ₖ₎ for the k-th job run, so pair the largest multipliers with the smallest bursts (rearrangement inequality). |
| Greedy algorithms | Job Sequencing Problem | Deadline sort + min-heap — keep the best ≤ d jobs in a heap | O(n log n) | O(n) | Placing a job in the earliest free slot — blocks tighter deadlines later. | Classic exchange-argument greedy. Give the slot-array version first (easy to explain), then speed it up: DSU "next free slot to the left" or the deadline-sorted min-heap. |
| Greedy algorithms | N Meetings in One Room | Sort by end, pick compatible — if start > lastEnd: take it | O(n log n) | O(n) | Sorting by start or by duration. | The canonical greedy proof: "greedy stays ahead" — after k picks, greedy's k-th end time ≤ any optimal schedule's k-th end time, so greedy can always fit at least as many. Be precise about strict vs n |
| Greedy algorithms | Non-overlapping Intervals | Sort by end, count keepers — keep if start ≥ lastEnd; answer n − kept | O(n log n) | O(1) extra | Initialising last = 0 with negative starts. | Recognise it as N Meetings in disguise and say so. A common follow-up: "sort by start instead?" — works too if, on overlap, you keep the interval with the smaller end. |
| Greedy algorithms | Insert Interval | Three-phase scan — copy left · absorb overlaps · copy right | O(n) | O(n) output | Using ≤ in phase 1 (end ≤ s) — then a touching interval isn't merged. | Not really greedy — it's careful boundary handling. Say the three phases out loud and nail the comparisons: left run is end < s, overlap run is start ≤ e. |
| Greedy algorithms | Merge Intervals | Sort + single pass — if start ≤ last.end: extend, else push | O(n log n) | O(n) output | out[-1][1] = e instead of max(...) — breaks on nested intervals. | Top-5 most-asked array question at Google. Write it clean in 5 minutes; the follow-ups (streaming input, already-sorted input, interval trees) are where the signal is. |
| Greedy algorithms | Minimum Number of Platforms | Sorted events, two pointers — if arr[i] ≤ dep[j]: +1 else −1 | O(n log n) | O(1) extra | Using < and undercounting at ties. | Same as Meeting Rooms II (LC 253). Two clean solutions: separate-sort two pointers, or a min-heap of departure times. Clarify the tie rule — it decides <= vs <. |
| Greedy algorithms | Valid Parenthesis String | Greedy balance range — lo/hi of possible open counts | O(n) | O(1) | Not clamping lo at 0 (keeps impossible negative balances). | Show recursion (3-way branch) → memoised DP on (index, balance) → O(n) greedy range. The greedy's correctness: every balance in [lo, hi] is achievable, and the set stays contiguous. |
| Greedy algorithms | Candy | Slope counting, O(1) space — sum peaks and valleys as triangles | O(n) | O(1) | Taking L[i] + R[i] − 1 or a sum instead of the max. | Expected answer: two passes O(n)/O(n). Bonus: the O(1)-space slope-counting solution — walk up-slopes and down-slopes and add triangle numbers, fixing the peak with a max. |
| Greedy algorithms | Jump Game II | Greedy level window — [l, r] window per jump; next r = max(i + nums[i]) | O(n) | O(1) | Jumping to the index with the biggest nums[i] instead of the biggest i + nums[i]. | Name it as BFS on a graph where index i has edges to i+1…i+nums[i], then show that BFS layers are contiguous ranges, so the queue collapses to two integers. That framing is what earns the hire signal. |
| Greedy algorithms | Minimum coins (greedy, canonical denominations) | Greedy with division — take V // c copies of each coin | O(k + answer) | O(answer) | Using greedy on non-canonical coin sets (e.g. {1, 3, 4}). | Give the greedy answer immediately, then say *why* it is only correct here: the denomination system is canonical. Offer the {1, 3, 4} counterexample unprompted, and name DP coin change as the general |
| Sliding window and 2 pointer | Maximum Points You Can Obtain from Cards | Slide the split — start with k left cards, swap one left for one right k times | O(k) | O(1) | Greedily taking the larger end card each step: [1, 1000, 1, 1, 1] style inputs where a small card hides a big one. | Candidates often start a recursion of left/right choices (2^k). The interviewer wants the observation that the choices collapse to k + 1 splits. Either form (slide the split, or minimise the middle |
| Sliding window and 2 pointer | Longest Substring Without Repeating Characters | Window with last-seen index (jump) — l = max(l, last[c] + 1) | O(n) | O(Σ) | l = last[c] + 1 without the ≥ l check, which moves l backwards on inputs like "abba". | The canonical variable window. Expect to explain the invariant (window has no duplicates), why l never moves left (max(l, last[c] + 1)), and the O(1) alphabet space. |
| Sliding window and 2 pointer | Max Consecutive Ones III | Non-shrinking window — if zeros > k: move l once | O(n) | O(1) | Counting flipped 1s instead of zeros. | The rephrase is the whole problem: "flip at most k" is "window with at most k zeros". Interviewers like the no-shrink trick as a follow-up; know why it's correct. |
| Sliding window and 2 pointer | Fruit Into Baskets | Window with counts — shrink while > 2 keys | O(n) | O(1) | Forgetting to delete keys at count 0, so the map size never drops. | A disguised template problem. Say the rephrase first; then the code is the standard at-most-K window. Mention that removing a key at count 0 is what keeps len(map) honest. |
| Sliding window and 2 pointer | Longest Substring With At Most K Distinct Characters | Window with counts and a distinct counter — shrink while distinct > k | O(n) | O(Σ) | Incrementing distinct on every new character instead of on 0 → 1. | The generalised template. Interviewers check the distinct counter maintenance (increment on 0 → 1, decrement on 1 → 0) and the k = 0 edge. |
| Sliding window and 2 pointer | Longest Repeating Character Replacement | Window with a stale maxFreq — maxFreq only increases; shrink by one | O(n) | O(Σ) | Validity check len − maxFreq < k (should be ≤ k, i.e. shrink when > k). | Asked to test the stale-maxFreq insight. Give the O(26n) version (recompute max on shrink) first if unsure, then explain why maxFreq can stay stale. |
| Sliding window and 2 pointer | Minimum Window Substring | Window with a deficit counter — expand until need == 0, then shrink | O( | s | + | t | ) | O(Σ) | Checking coverage by comparing two maps each step (O(Σ) per step, and easy to get wrong with duplicates). | The hardest standard window. Explain the need counter: decrement it only when a character fills a real deficit (cnt[c] > 0 before decrementing); increment only when removing a character creates on |
| Sliding window and 2 pointer | Minimum Window Subsequence | Forward match + backward shrink — find an end, walk back to the tightest start | O(n·m) | O(1) | Using the Minimum Window Substring counter, which ignores order. | Not a counting window: order matters, so the need counter doesn't work. The forward/backward scan is the expected answer; mention the O(n·m) DP as an alternative. |
| Sliding window and 2 pointer | Number of Substrings Containing All Three Characters | Last-seen positions — add 1 + min(last) per right end | O(n) | O(1) | Adding min(last) without the +1 (starts are 0-indexed, so there are min + 1 of them). | "At least" counting. Two accepted answers: the last-seen trick (count by right end) or the window that adds n − r for each valid left. Show you know why +1 + min(last) counts starts 0..min. |
| Sliding window and 2 pointer | Binary Subarrays With Sum | atMost(goal) − atMost(goal − 1) — two at-most windows | O(n) | O(1) | A single exact-sum window with while sum > goal — misses windows that differ by leading zeros. | The canonical place to introduce the atMost subtraction. Mention that a plain "shrink while sum > goal" window undercounts because of zeros, and that prefix sums are the fallback for non-binary arrays |
| Sliding window and 2 pointer | Count Number of Nice Subarrays | atMost(k) − atMost(k − 1) — window on the odd count | O(n) | O(1) | Missing the reduction and writing a custom window that undercounts even runs. | Tests whether you spot the reduction. Say "odd → 1, even → 0, now it's binary subarrays with sum k" and reuse the code. |
| Sliding window and 2 pointer | Subarrays with K Different Integers | atMost(k) − atMost(k − 1) — two at-most-distinct windows | O(n) | O(n) | One window that counts when distinct == k — misses all starts between the leftmost and rightmost valid ones. | The hard capstone of the atMost trick. Explain why a direct exactly-k window fails (for a fixed r, the valid starts form a range in the middle, not a prefix) and why subtraction fixes it. |
| Stack and queues | Implement Stack using Arrays | Growable array (capacity doubling) — when full, copy into an array twice the size | O(1) amortised | O(n) | Mixing up t as top index and as size, which causes off-by-one on top(). | A warm-up. What the interviewer checks: the empty/full guards, consistent t semantics (index of the top, not one past it), and whether you can explain why doubling (not +1) gives amortised O(1). |
| Stack and queues | Implement Queue using Arrays | Circular buffer (with doubling) — front + count, indices mod cap | O(1) amortised | O(n) | front == rear used for both empty and full. Keep a count or leave one slot unused. | The trap is the naive pop(0) / shifting version, which makes dequeue O(n). Also, front == rear alone can't tell full from empty. Keep a count (or waste one slot) and say which convention you cho |
| Stack and queues | Implement Stack using Queue | One queue, rotate on push — enqueue x, then cycle size−1 elements behind it | push O(n), pop O(1) | O(n) | Rotating size times instead of size − 1, which puts x back at the end. | Say up front which operation you make O(n) and why. Rotating on push keeps pop/top O(1). The two-queue version is the textbook answer; the one-queue rotate is the cleaner follow-up. |
| Stack and queues | Implement Queue using Stack | Two stacks, lazy transfer — pour in → out only when out is empty | O(1) amortised | O(n) | Pouring when out is non-empty, which puts newer elements above older ones. | This is an amortised-analysis question. Explain why the transfer is lazy (only when out is empty) and why each element crosses at most once. Transferring back and forth on every op is the common O(n |
| Stack and queues | Implement stack using Linkedlist | Head = top — push: new node → old head; pop: head = head.next | O(1) per op | O(n) | Using the tail as top: pop then needs the predecessor, so it's O(n). | Expect the follow-up: array or linked list, which is better? The answer covers amortised vs worst-case O(1), memory overhead per node, and cache locality. Also free the popped node in C++. |
| Stack and queues | Implement queue using Linkedlist | Head = front, tail = back — enqueue: tail.next = node; dequeue: head = head.next | O(1) per op | O(n) | Not resetting tail after the last pop, so the next push links onto a dead node. | The bug they're looking for: after popping the last node, tail still points to the freed node. Reset tail = null when head becomes null. |
| Stack and queues | Balanced Paranthesis | Stack of openers — push openers; closer must match the top | O(n) | O(n) | Returning true without checking the stack is empty at the end. | Basic, but the three failure modes must all be handled: wrong type, a closer with an empty stack, and leftover openers. A quick early exit: odd length → false. |
| Stack and queues | Infix to Postfix Conversion | Shunting-yard (operator stack) — pop while top binds tighter, then push | O(n) | O(n) | Popping on equal precedence for ^, which gives ab^c^ for a^b^c. | The interviewer checks precedence and associativity. Write out the pop condition: prec(top) > prec(c), or equal precedence and c is left-associative. Getting a^b^c right is the tell. |
| Stack and queues | Infix to Prefix Conversion | Reverse, convert, reverse — mirror the string, postfix with flipped ties, mirror back | O(n) | O(n) | Keeping the postfix tie rule after reversing, which turns a-b-c into -a-bc (that's a−(b−c)). | Most candidates remember the reverse trick but get the tie-break wrong, so test a-b-c out loud. The recursive-descent version avoids the trick entirely and is easier to defend. |
| Stack and queues | Prefix to Infix Conversion | Operand stack — scan right to left; operator combines the top two | O(n²) strings · O(n) with a tree | O(n) | Popping in the wrong order (b first), which mirrors non-commutative operators like − and /. | These conversions all use one idea: an operand stack of finished sub-expressions. Know the scan direction (prefix → right-to-left, postfix → left-to-right) and which pop is the left operand. |
| Stack and queues | Prefix to Postfix Conversion | Operand stack — scan right to left; operator combines the top two | O(n²) strings · O(n) with a tree | O(n) | Reversing the operand order. | These conversions all use one idea: an operand stack of finished sub-expressions. Know the scan direction (prefix → right-to-left, postfix → left-to-right) and which pop is the left operand. |
| Stack and queues | Postfix to Infix Conversion | Operand stack — scan left to right; operator combines the top two | O(n²) strings · O(n) with a tree | O(n) | a = pop() first: ab- becomes (b-a). | These conversions all use one idea: an operand stack of finished sub-expressions. Know the scan direction (prefix → right-to-left, postfix → left-to-right) and which pop is the left operand. |
| Stack and queues | Postfix to Prefix Conversion | Operand stack — scan left to right; operator combines the top two | O(n²) strings · O(n) with a tree | O(n) | Wrong pop order. | These conversions all use one idea: an operand stack of finished sub-expressions. Know the scan direction (prefix → right-to-left, postfix → left-to-right) and which pop is the left operand. |
| Stack and queues | Next Greater Element | Monotonic stack, right to left — pop ≤ current, top is the answer, push current | O(n) | O(n) | Popping only on <, which returns an equal value as 'greater'. | This is the template behind the whole section. Say the invariant out loud: the stack holds candidates in decreasing order, and each element is pushed and popped once, so it's O(n). LC 496 is the same |
| Stack and queues | Next Greater Element - 2 | Monotonic stack over 2n — right-to-left from 2n−1, answer only for i < n | O(n) | O(n) | Allocating a real doubled array (works, wastes memory) and then returning 2n answers. | The modulo trick is what they want. Don't actually allocate the doubled array; index with i % n. The maximum element is always −1 (and so are its duplicates). |
| Stack and queues | Asteroid Collision | Stack of survivors — new left-mover fights right-moving tops | O(n) | O(n) | Colliding when the top is negative and the new one positive: they move apart. | State the collision condition precisely: only top > 0 and cur < 0. Many candidates also collide top < 0, cur > 0, but those move apart. Then handle the three outcomes cleanly with a flag or a loop |
| Stack and queues | Sum of Subarray Minimums | Contribution with previous/next smaller — arr[i]·(i − pse)·(nse − i) | O(n) | O(n) | Strict comparison on both sides, which double-counts subarrays with repeated minimums. | This is the key 'contribution' problem. Interviewers probe the tie-break: with [2,2], if both sides use strict <, the subarray [2,2] is counted twice. Explain why one side must be ≤. |
| Stack and queues | Sum of Subarray Ranges | Σ max − Σ min via monotonic stacks — contribution as max minus contribution as min | O(n) | O(n) | Same strictness on both sides (double counting with duplicates). | The O(n²) running max/min is acceptable at n = 1000. The follow-up asks for O(n), which is the contribution method run twice. Note there's no modulo here, so use 64-bit. |
| Stack and queues | Remove K Digits | Monotonic stack — pop larger tops while k > 0, then trim | O(n) | O(n) | Forgetting the leftover-k trim, so "12345" stays unchanged. | Prove the greedy in one line: in two candidates of the same length, the first differing position decides, so removing the first 'peak' (a digit greater than its successor) is never worse. Then nail th |
| Stack and queues | Next Smaller Element | Monotonic stack, right to left — pop ≥ current, top is the answer, push | O(n) | O(n) | Popping on > only, which returns equal values. | Usually asked together with NGE or as a sub-step. Have all four variants straight: next/previous × greater/smaller. Each is the same loop with a flipped comparison or direction. |
| Stack and queues | Implement Min Stack | Single stack + encoded values — push 2x − min when x is a new min | O(1) all ops | O(1) extra beyond the values | Separate min-stack that only pushes on x < min: then popping a duplicate minimum loses it. Push on ≤. | Lead with the pair stack; it's clear and obviously correct. Offer the 2x − min encoding as the space follow-up, and mention it needs 64-bit arithmetic because 2x − min can overflow int. |
| Stack and queues | Sliding Window Maximum | Monotonic deque of indices — pop expired front, pop smaller back, push, read front | O(n) | O(k) | Storing values instead of indices (can't detect expiry). | The canonical monotonic-deque problem. Say why indices, not values: you need indices to know when the front leaves the window. Cover both pops: the front (expiry) and the back (dominance). |
| Stack and queues | Trapping Rainwater | Two pointers — move the lower side; its running max decides its water | O(n) | O(1) | Forgetting to include h[i] itself in maxLeft/maxRight, which gives negative water. | Walk the ladder: brute (per-bar scans) → prefix/suffix arrays → two pointers with O(1) space. The two-pointer proof is what they probe: when h[l] < h[r], there is a bar of height ≥ h[r] > h[l] on |
| Stack and queues | Largest rectangle in a histogram | One pass, compute on pop — sentinel 0 at the end; area when a bar is popped | O(n) | O(n) | Forgetting the sentinel, which leaves bars on the stack unprocessed. | Top-5 stack problem. Explain the 'shortest bar' argument first, then the two-pass PSE/NSE solution, then fold it into one pass with a sentinel height 0 at the end to flush the stack. |
| Stack and queues | Maximum Rectangles | Histogram per row + monotonic stack — update heights, run largest-rectangle per row | O(R·C) | O(C) | Not resetting height to 0 on a 0 cell (columns aren't contiguous). | Recognising the reduction is the whole problem. Say it in one sentence: 'every rectangle has a bottom row; for that row, column heights form a histogram.' Reuse the histogram routine as a helper. |
| Stack and queues | Stock span problem | Stack of (price, span) — pop ≤ price, add their spans | O(1) amortised | O(n) | Using < (equal-priced days would not be absorbed). | Name it as 'previous greater element, distance form'. The trick for the online version is storing the span with each price so popped days are counted without being stored. |
| Stack and queues | The Celebrity Problem | Single-candidate elimination — candidate = i whenever candidate knows i; then verify | O(n) | O(1) | Returning the candidate without verifying. | The eliminate-one-per-query argument is what they want. The classic presentation pushes everyone onto a stack and pops two at a time; the single-candidate loop is the same idea without the stack. Don' |
| Stack and queues | LRU Cache | Hashmap + doubly linked list — map key → node; DLL head = most recent | O(1) per op | O(capacity) | Not storing the key in the node, so eviction can't remove the map entry. | Expect to write the DLL by hand (no OrderedDict / LinkedHashMap unless they allow it; mention that you know them). Keep two helpers, remove(node) and insertFront(node), and build both operatio |
| Stack and queues | LFU Cache | Frequency buckets + minFreq — freq → ordered set of keys; evict LRU of minFreq | O(1) per op | O(capacity) | Not updating minFreq when its bucket empties on touch. | Hard design problem; correctness of minFreq is the usual bug. Explain why minFreq only ever needs to increase by 1 on access (the touched key moves to f + 1, which then becomes the new minimum) |
| Stack and queues | Number of Greater Elements to the Right | Merge-sort counting for all indices — on merge, left x gains (#remaining right) | O(n log n + q) | O(n) | Using a monotonic stack: popped elements are lost but still count for earlier indices. | The sheet places this here to test whether you'll wrongly reach for a monotonic stack. Say why it fails: popped elements still count for future queries. With few queries, brute force is optimal (O(n·q |
| Binary trees | Inorder Traversal | Iterative with explicit stack — push left spine; pop → visit → go right | O(n) | O(h) | Loop condition while st only, which exits immediately because the stack starts empty. | Expect the follow-up "now without recursion". The iterative version is a template you reuse for kth smallest in BST, the BST iterator and validating a BST, so write it from memory. Morris (O(1) space) |
| Binary trees | Preorder Traversal | Iterative stack — pop → visit → push right, push left | O(n) | O(h) | Pushing left before right, which gives Root→Right→Left. | Preorder is the 'top-down' traversal. A parent is seen before its children, so it's how you copy or serialise a tree and how you pass state (depth, path sum, bounds) downward. |
| Binary trees | Postorder Traversal | One stack + last visited — descend left; at top: go right unless right is done; else visit | O(n) | O(h) | Comparing values instead of node identity for last (fails with duplicate values). | Postorder is the 'bottom-up' traversal. Height, diameter, balanced check, max path sum and tree DP all compute a node's answer from its children's answers. The two-stack trick (reverse of Root-R-L) is |
| Binary trees | Level Order Traversal | BFS with level snapshot — for _ in range(len(q)): pop, record, push children | O(n) | O(w) | Calling len(q) inside the loop condition, so the level boundary moves as children are enqueued. | The level-size snapshot is the core template for zigzag, right view, max width, level averages, minimum depth, burning tree and nodes at distance K. Mention that BFS space is O(w), the max width, up t |
| Binary trees | Pre, Post, Inorder in one traversal | Stack of (node, state) — state 1 pre→left · 2 in→right · 3 post→pop | O(n) | O(h) | Popping in state 1 or 2: the node must stay on the stack until state 3. | The point is to show you understand recursion as a state machine. Recursion reaches every node three times: on entry, between the two children, and on exit. The (node, state) stack makes those three m |
| Binary trees | Maximum Depth in BT | Recursive postorder — 1 + max(L, R) | O(n) | O(h) | Returning −1 for null and mixing up the edges/nodes conventions. | Clarify the convention: nodes vs edges (LC counts nodes; some textbooks count edges, so a single node has height 0). Write the recursive one-liner, then mention BFS counting levels as the stack-safe a |
| Binary trees | Check if two trees are identical or not | Recursive lock-step — null checks, value check, recurse both sides | O(min(n, m)) | O(min(h₁, h₂)) | Comparing only preorder (or only inorder) without null markers. | A building block for *Subtree of Another Tree* (LC 572) and *Symmetric Tree*. Note why comparing a single traversal is wrong: [1,2] and [1,null,2] have the same preorder 1,2. You need null marke |
| Binary trees | Check for balanced binary tree | Bottom-up height with −1 sentinel — h = −1 if a child is −1 or | hl − hr | > 1 | O(n) | O(h) | Checking only the root's two heights. | The naive version calls height() at every node, which is O(n²) on a skewed tree. The interviewer wants you to fold the check into the height computation. 'Return a sentinel or a pair from postorder' |
| Binary trees | Diameter of Binary Tree | Single postorder pass — best = max(best, hl + hr); return 1 + max(hl, hr) | O(n) | O(h) | Returning hl + hr up the tree instead of the height. | The trap is assuming the path goes through the root. The last test has a longer path entirely inside the left subtree. Explain the 'return height, record diameter' split clearly, because max path sum |
| Binary trees | Maximum path sum | Single postorder pass — g = val + max(0, gL, gR); best = max(best, val + max(0,gL) + max(0,gR)) | O(n) | O(h) | best = 0 initial value (wrong for all-negative trees). | A classic Google/FAANG hard. Name both quantities out loud: the *return* value (a path going down one side, extendable by the parent) and the *answer* (a path that may use both sides, not extendable). |
| Binary trees | Check for symmetrical BTs | Recursive mirror check — m(a,b) = a.val==b.val ∧ m(a.l,b.r) ∧ m(a.r,b.l) | O(n) | O(h) | Comparing a.left with b.left (that's *same tree*). | Recursive first, then the iterative queue version: push pairs (outer, outer), (inner, inner). A common wrong idea is 'inorder is a palindrome'. Test 5 ([1,2,2,2,null,2]) has a palindromic inorder bu |
| Binary trees | Children Sum Property in Binary Tree | Push down, sum up — pre: if childSum < val → children = val else val = childSum; post: val = L + R | O(n) | O(h) | Overwriting a leaf with 0 in the post-step (only internal nodes are re-summed). | Striver's O(n) trick. The GfG *check* version is a trivial DFS. The *convert* version is the interesting one. Explain why pushing the parent's value down is safe: it only makes subtrees larger, and la |
| Binary trees | Zig Zag Traversal Of Binary Tree | BFS + index placement — lvl[i] or lvl[size−1−i] depending on direction | O(n) | O(w) | Enqueuing right-before-left on odd levels: this scrambles the next level. | Say clearly that the queue order never changes; only the output index does. The two-stack version (one stack per direction) is the classic alternative. Mention it, but the flag version is shorter and |
| Binary trees | Boundary Traversal of a Binary Tree | Left edge + leaves + reversed right edge — three loops, leaves via DFS | O(n) | O(h) | Including leaves in the left/right edge walk (double count). | It's all about edge cases, so state the three-part definition before coding. Common bugs: double-counting a leaf that is also on the left edge, adding the root twice when it is a leaf, and forgetting |
| Binary trees | Vertical Order Traversal | Collect triples + one sort — (col, row, val) for every node, sort, group by col | O(n log n) | O(n) | Using BFS order for ties (that's LC 314, not 987). | Ask about the tie rule first. LC 314 (premium) keeps BFS order for ties, and LC 987 sorts by value, so the answer depends on it. Striver's version uses map<col, map<row, multiset>>, which is equival |
| Binary trees | Top View of Binary Tree | BFS + first-seen per HD — queue of (node, hd); record if hd unseen | O(n) | O(n) | DFS with 'first visit wins': a left-subtree node can reach HD +1 before the right child does. | The usual follow-up is 'why not DFS?'. With DFS you have to keep (depth, value) per column and replace only on a smaller depth. That works, but BFS gets it right by construction. Keep track of min/max |
| Binary trees | Bottom view of Binary Tree | BFS + overwrite per HD — queue of (node, hd); seen[hd] = val every time | O(n) | O(n) | DFS with 'last visit wins' and no depth check (a shallow right-subtree node can overwrite a deeper left-subtree node). | Say the tie rule out loud ('later in level order'). That rule is why BFS is the natural fit. A DFS version needs (depth, val) and >= on the depth with a right-after-left visit order. |
| Binary trees | Right/Left View of Binary Tree | DFS: first node per depth — right view: visit R before L; append when depth == len(res) | O(n) | O(h) | Walking only the right edge (cur = cur.right). | Show both versions: BFS (last of each level) and the shorter DFS. The trap is assuming the right view is the right edge. Test 5 shows a left-subtree node visible from the right because the right subtr |
| Binary trees | Print root to node path in BT | DFS + backtracking — append; if leaf copy; recurse; pop | O(n·h) (copies at leaves) | O(h) + output | Appending path itself (all entries alias the same list, which ends up empty). | This is the backtracking skeleton you reuse for path sum II and for LCA via paths. For the target-node variant, return a boolean so recursion stops as soon as the target is found and the path is kept, |
| Binary trees | LCA in BT | Single postorder — if n in {p,q,null} return n; L,R; both → n else L or R | O(n) | O(h) | Comparing values when duplicates are possible (compare node identity). | The short recursion is expected. Be ready to justify the case where p is an ancestor of q: we return p without looking below it, which is right because the LCA is p. If the guarantee that both exist i |
| Binary trees | Maximum width of a Binary Tree | BFS + normalised heap index — idx -= first of level; children 2i+1, 2i+2 | O(n) | O(w) | Counting only non-null nodes per level (that's not the width). | The overflow is the interview point. A skewed-zigzag tree of depth 3000 gives indices of 2³⁰⁰⁰. Python hides it with big ints; C++/Java need the per-level offset trick (or unsigned wraparound, which w |
| Binary trees | Print all the Nodes at a distance of K in a BT | Parent map + BFS from target — map child→parent, then K BFS rounds over {L, R, parent} | O(n) | O(n) | No visited set: BFS bounces between a node and its parent forever. | Name the transformation: tree → graph via parent pointers. The same idea solves 'burn the tree' and 'min time to infect'. A DFS-only alternative returns the distance-to-target from each subtree and co |
| Binary trees | Minimum time taken to burn the BT from a given Node | Parent map + BFS — find start + parents, BFS over {L, R, parent} counting rounds | O(n) | O(n) | Counting the final empty round (off by one): only count rounds that ignite something. | It's distance-K again: count rounds until the queue empties instead of stopping at k. The one-pass DFS (combining depth and distance-to-start) is an elegant O(n)/O(h) alternative, but explaining it un |
| Binary trees | Count total Nodes in a COMPLETE BT | Left/right height shortcut — hl == hr → 2^h − 1 else 1 + rec(L) + rec(R) | O(log² n) | O(log n) | Comparing height(left) vs height(right) with full height functions (O(n) per call). | State the complexity argument: when the left and right heights differ, at least one child subtree is perfect and returns in O(log n). Only one path is ever explored deeply, which gives O(log² n). The |
| Binary trees | Flatten Binary Tree to LinkedList | Morris-style rewiring — pred = rightmost(left); pred.right = cur.right; cur.right = cur.left; cur.left = null | O(n) | O(1) | Forgetting cur.left = null, which leaves a cycle-looking structure that fails the check. | Three versions, and Striver covers all three. (1) Reverse preorder (R, L, root) with a prev pointer: node.right = prev; node.left = null; prev = node. (2) Stack: push right then left, and link to |
| Binary trees | Requirements needed to construct a unique BT | Case check — exactly one is inorder and they differ | O(1) | O(1) | Saying pre + post works in general. | The counterexample is the whole answer. With pre [1,2] and post [2,1], node 2 can be either the left or the right child. Pre + post is enough only for a full binary tree (every node has 0 or 2 |
| Binary trees | Construct a BT from Preorder and Inorder | Bounds + hash map — pos[val] = inorder index; build(preL, preR, inL, inR) | O(n) | O(n) | Off-by-one in the preorder split: left part is pL+1 .. pL+leftSize. | Write the recursion with four bounds (preL, preR, inL, inR) or the shorter 'global preorder pointer' version. Either way, mention why slicing is O(n²) and the hash map is mandatory. Deep skewed inpu |
| Binary trees | Construct a BT from Postorder and Inorder | Bounds + hash map — root = post[pR]; left size = k − iL | O(n) | O(n) | Global-pointer version building left before right (wrong tree). | Show you understand the symmetry rather than memorising two solutions: preorder reads root-first from the left, postorder reads root-first from the right. With a global pointer, the order of the recur |
| Binary trees | Serialize and De-serialize BT | Level order with '#' — BFS writes every child slot; decoder BFS pops two tokens per node | O(n) | O(n) | No null markers (preorder alone is ambiguous). | Ask whether the codec must be stateless (yes: no globals). Pick a delimiter so negative and multi-digit values are safe. Preorder + # is the shortest to write. BFS avoids recursion depth issues on s |
| Binary trees | Morris Inorder Traversal | Morris inorder — no left → visit, go right; else find pred: no thread → make it, go left; thread → cut, visit, go right | O(n) | O(1) | Missing the pred.right != cur stop condition, which loops forever around the thread. | Draw the thread, then show why it's O(n): every edge on a predecessor path is walked at most twice (once to create the thread, once to remove it). Mention it's not safe for concurrent readers, since t |
| Binary trees | Morris Preorder Traversal | Morris preorder — no left → visit, right; pred unthreaded → visit, thread, left; threaded → cut, right | O(n) | O(1) | Also outputting when removing the thread (duplicates). | Present it as a one-line diff from Morris inorder. That shows you understand the mechanism rather than memorising two programs. The thread logic is untouched; only the output moves. |
| Binary search trees | Search in BST | Iterative walk — while cur and cur.val != val: step left/right | O(h) | O(1) | Searching both subtrees (O(n)), which ignores the invariant. | This is a warm-up. State O(h) and that h is log n only when the tree is balanced. The walk becomes the skeleton of floor/ceil, insert, delete, LCA and successor, so write it cleanly. |
| Binary search trees | Floor and Ceil in a BST | Single walk per side — right-step → floor candidate; left-step → ceil candidate | O(h) | O(1) | Recording the candidate on the wrong turn (floor is recorded when moving right). | It's the BST version of lower/upper bound. Say that out loud. TreeMap.floorKey/ceilingKey and std::set::lower_bound do the same walk on a balanced tree. |
| Binary search trees | Minimum and Maximum in BST | Spine walks — leftmost = min, rightmost = max | O(h) | O(1) | Taking the leftmost *leaf* rather than the leftmost *node*: the min may have a right child. | Mention that in a plain binary tree this needs a full O(n) traversal, while the BST makes it O(h). That contrast is the point of the question. |
| Binary search trees | Insert a given node in BST | Iterative — walk until the needed child is null, attach | O(h) | O(1) | Walking to cur = null and then trying to attach: you've lost the parent. | Watch the empty-tree case: the function has to *return* the new root. The recursive root.left = insert(root.left, val) pattern returns subtree roots; delete reuses it, so learn it here. |
| Binary search trees | Delete a node in BST | Iterative, splice — find parent; replace child with helper(child) | O(h) | O(1) | Not returning the new root when the root itself is deleted. | Name the three cases before you code. The successor-copy method is the textbook answer and keeps the height change small. The splice is shorter but can deepen the tree. Either is accepted; say which y |
| Binary search trees | Kth Smallest and Largest element in BST | Iterative inorder, early stop — kth pop of inorder; kth pop of reverse inorder | O(h + k) | O(h) | Using a global counter in recursion without stopping the remaining calls (still O(n)). | The follow-up is 'what if the BST is modified often and you query kth repeatedly?' Augment each node with its subtree size; then kth is an O(h) walk. Kth largest also equals the (n − k + 1)th smallest |
| Binary search trees | Check if a tree is a BST or not | Bounds recursion — valid(n, lo, hi): lo < n.val < hi, recurse with narrowed window | O(n) | O(h) | Checking only left.val < val < right.val. | The values reach the int limits, so INT_MIN/INT_MAX sentinels break on [2147483647]. Use long, nullable bounds, or ±∞ in Python. Interviewers try exactly this input. |
| Binary search trees | LCA in BST | Iterative split — loop until p and q fall on different sides | O(h) | O(1) | Using the general binary-tree LCA (correct but O(n), misses the point). | Contrast it with LCA in a general binary tree (O(n), post-order). Here ordering gives O(h) and O(1) space. If the nodes might not exist, verify with two searches. |
| Binary search trees | Construct a BST from a preorder traversal | Upper-bound recursion — build(bound): take pre[i] if < bound; left = build(val), right = build(bound) | O(n) | O(h) | Passing the index by value, so the recursion re-reads the same element. | Give all three approaches with their costs: n inserts O(n²) worst; sort to get the inorder and use the pre+in build O(n log n); upper-bound recursion O(n). The last is the one they want. |
| Binary search trees | Inorder successor and predecessor in BST | Two candidate walks — succ: go left → record; pred: go right → record | O(h) | O(1) | Going left on equality for the successor (you'd record smaller values). | The textbook answer has two cases: if the node has a right child, the successor is the leftmost of it; otherwise it's the nearest ancestor you went left from. The candidate walk below handles both cas |
| Binary search trees | BST iterator | Stack of left spine — push left spine; next = pop + push left spine of right | O(1) amortised | O(h) | Pushing the whole tree in the constructor (that's the O(n) list in disguise). | The interviewer wants the O(h)-memory version and an explanation of 'amortised O(1)'. Over all calls each node is pushed once and popped once, so n calls cost O(n) in total. A single next() can cost |
| Binary search trees | Two sum in BST | Two BST iterators — lo = next(), hi = before(); move the side that fixes the sum | O(n) | O(h) | Pairing a node with itself (k = 2·val). | Three answers, each better on one axis: a hash set during DFS (O(n)/O(n), works on any tree); inorder array + two pointers (O(n)/O(n)); two iterators (O(n)/O(h)). The last uses the BST. Stop when the |
| Binary search trees | Correct BST with two nodes swapped | Inorder, track first/last violation — on prev > cur: first ← prev (once), last ← cur | O(n) | O(h) | Setting last = prev at the second descent (it must be cur). | Draw the inorder sequence and show both cases (adjacent vs distant swap). Recording first once and updating last at every descent covers both without special-casing. The O(1) follow-up is Morris i |
| Binary search trees | Largest BST in Binary Tree | Post-order (min, max, size) — valid iff l.max < val < r.min; invalid → (−∞, +∞, best) | O(n) | O(h) | Checking only direct children instead of subtree min/max. | It's the most-asked 'combine validate-BST with post-order' problem. Explain the sentinel ranges carefully: the empty tree's (+∞, −∞) and the invalid subtree's (−∞, +∞) are what make the check one line |
| Heaps | Heapify Algorithm | Sift up or sift down from ind — smaller → bubble up; larger → sink | O(log n) | O(1) | Sifting down by swapping with the left child instead of the smaller child, which breaks the right subtree. | This is the primitive behind every heap operation: push is 'append + sift up', pop is 'move last to root + sift down', decrease-key is 'sift up'. Say which direction and why before coding. |
| Heaps | Build heap from a given Array | Bottom-up sift-down — for i = n/2−1 … 0: siftDown(i) | O(n) | O(1) | Looping i upward from 0: children aren't heaps yet, so the result is wrong. | The follow-up is always 'why is it O(n) and not O(n log n)?'. Answer with the height sum: n/4 nodes sift ≤ 1 level, n/8 sift ≤ 2, …; Σ h/2^(h+1) converges to 1, so the total is ≤ n swaps. |
| Heaps | Implement Min Heap | Binary heap on an array — append+siftUp · swap last to root+siftDown | push/pop O(log n), top/size O(1) | O(n) | pop moves the last element to the root after removing it: with one element you'd write it back into an empty array. | Write siftUp and siftDown as helpers first, then each public method is 2–3 lines. Mention changeKey(i, v) = assign + (sift up or down) and that it needs an index map if callers refer to items ra |
| Heaps | Implement Max Heap | Binary heap with a priority predicate — higher(i, j) = a[i] > a[j] | push/pop O(log n) | O(n) | Flipping only one of the two sift comparisons. | Ask whether they want a generic heap: one comparator (less(a, b) meaning 'a should be nearer the root') covers min, max and pair/tuple ordering. In Python, show the negation trick for heapq too. |
| Heaps | Check if an array represents a min heap | Loop over internal nodes — for i < n/2: check both children | O(n) | O(1) | Using <= in the failure test, which rejects equal keys. | One loop. Mention that the same idea checks a max-heap by flipping the comparison, and that the transitivity of ≤ is why checking edges is enough (grandparent ≤ parent ≤ child). |
| Heaps | Convert Min Heap to Max Heap | Bottom-up max-heapify — for i = n/2−1 … 0: siftDown toward the larger child | O(n) | O(1) | Reversing the array: [1,2,3,4,5] reversed is [5,4,3,2,1] (OK by luck), but [1,3,2] reversed is [2,3,1], which is not a max-heap. | The trap is trying to 'reverse' the heap or swap levels. A reversed min-heap isn't a max-heap in general. State the O(n) build, and point out that the min-heap input helps nothing (and costs nothing). |
| Heaps | Heap Sort | In-place heap sort — max-heapify; swap root to end; shrink; sift down | O(n log n) | O(1) | Using a min-heap for ascending in-place sort (the min lands at the end). | Contrast it with the others: heap sort gets O(n log n) worst case and O(1) space (merge sort needs O(n) space, quicksort is O(n²) worst case), but it's not stable and has poor cache locality, |
| Heaps | K-th Largest element in an array | Quickselect (3-way partition) — partition around pivot; recurse into the side holding index n−k | O(n) expected | O(1) | Using a max-heap of all n and popping k times: O(n + k log n), fine, but not the bounded-memory answer they want. | Give all three and their trade-offs: sort O(n log n); heap O(n log k), streaming-friendly, deterministic; quickselect O(n) expected and O(n²) worst case (random pivot, 3-way partition for duplicates). |
| Heaps | Kth largest element in a stream of running integers | Min-heap of size k — push; pop while size > k; return root | add O(log k) | O(k) | Using a max-heap of everything and popping k times per query: O(k log n) per add. | The interviewer is checking that you pick a min-heap (not max) and cap it at k. Say why: you need to evict the smallest of the top k, which is exactly the min-heap root. Mention that the construct |
| Heaps | Sort K sorted array | Min-heap of size k+1 — seed k+1; pop min to output, push next | O(n log k) | O(k) | Heap of size k instead of k+1 (misses the element exactly k away). | Prove the window size: the smallest remaining element is at most k positions to the right of the next output slot, so k+1 candidates suffice. Note that insertion sort is also O(nk) on this input, whic |
| Heaps | Merge K sorted Lists | Min-heap of heads — pop smallest head, append, push its next | O(N log k) | O(k) | Python: heap of bare ListNodes raises TypeError on ties (no <); add an index tie-breaker. | Present heap and divide-and-conquer; both are O(N log k). The heap version is the template for external sorting and the Twitter feed. Watch out for comparing nodes directly in Python (use `(val, idx, |
| Heaps | Replace elements by its rank in the array | Sort distinct values + hash map — rank[v] = index in sorted(set(arr)) + 1 | O(n log n) | O(n) | Ranking by sorted index without deduplicating: [100,100] would get [1,2]. | Sort + map is the expected answer. The heap version (pop in order, increment rank when the value changes) is what Striver uses to practise heaps; mention both and that both are O(n log n). |
| Heaps | Task Scheduler | Counting formula — max(T, (f−1)(n+1) + #tasks with freq f) | O(T) | O(26) | Forgetting the max(T, …): the frame undercounts when tasks overflow the gaps. | Lead with the heap simulation (it's the general technique: always run the most-remaining available task), then derive the formula from its structure. Explain why the max with len(tasks) is needed: |
| Heaps | Hand of Straights | Sorted distinct keys, batch groups — for x ascending: open c[x] groups at x | O(n log n) | O(n) | Starting groups from an arbitrary card (not the minimum). | State the exchange argument for 'start at the smallest' out loud; it's the whole proof. Early exit if n % groupSize ≠ 0. Same problem as LC 1296 (Divide Array in Sets of K Consecutive Numbers). |
| Heaps | Design twitter | Heap-based k-way merge — max-heap of (time, user, idx); pop ≤ 10, push predecessor | feed O(f + 10 log f) | O(users + tweets) | Sorting by tweet id instead of post time. | Drive it like a mini system design: data model first (tweets[user] = [(time, id)], follows[user] = set), then the feed as merge-k. Mention fan-out-on-write vs fan-out-on-read: this is read-time me |
| Heaps | Minimum cost to connect sticks | Min-heap greedy — pop two smallest, add cost, push sum | O(n log n) | O(n) | Joining greedily left-to-right in the given order. | Give the exchange argument: in an optimal merge tree the two smallest can be made siblings at the deepest level without increasing cost. Then the problem recurses on n − 1 sticks. Note the identical s |
| Heaps | Maximum Sum Combination | Max-heap best-first + visited — pop (i,j); push (i+1,j), (i,j+1) if unseen | O(n log n + K log K) | O(K) | No visited set: the same cell gets pushed twice and its sum is reported twice. | This is the same engine as LC 373 (k smallest pairs) and k-th smallest in a sorted matrix. Explain why the visited set is needed: (1,1) is reachable from both (0,1) and (1,0). The alternative is |
| Heaps | Find Median from Data Stream | Two heaps — low = max-heap, high = min-heap; | low | − | high | ∈ {0, 1} | add O(log n), median O(1) | O(n) | Integer division for the even case ((a + b) / 2 in C++/Java). | Write the insert as 'push to low, move low's top to high, rebalance if high got bigger'. Those three lines maintain both invariants without case analysis. Follow-ups: values in [0,100] → counting arra |
| Heaps | Top K Frequent Elements | Bucket sort by frequency — bucket[count] = values; scan from n down | O(n) | O(n) | Max-heap of all d values then k pops: fine, O(d + k log d), but not the bounded-memory answer. | The follow-up asks you to beat O(n log n). Bucket sort is O(n) because counts are bounded by n. Quickselect on the distinct values by count is O(d) expected. The heap version is the one that survives |
| Graphs | Traversal Techniques | BFS + iterative DFS — explicit stack, push neighbours reversed, mark on pop | O(V + E) | O(V + E) | BFS: marking visited on pop instead of push, so a node can be queued many times (still correct, but O(E) queue entries and wrong 'distance' if you track levels carelessly). | Say the invariant out loud. BFS: when a node is popped, every node closer to the source has already been popped, which is why BFS gives shortest paths on unweighted graphs. DFS: when go(u) returns, |
| Graphs | Connected Components | Adjacency list + BFS — build lists; BFS from each unvisited node | O(V + E) | O(V + E) | Only traversing from node 0, so other components are missed. | This outer loop ('for each node: if unvisited, traverse and count') is the skeleton for islands, provinces, cycle detection and bipartite checks on graphs that may be disconnected. Write it once and r |
| Graphs | Number of provinces | DFS on the matrix — for each unvisited city, DFS scanning its row | O(n²) | O(n) | Treating the diagonal M[i][i] = 1 as a new edge to process (harmless with visited, but wasteful in DSU without i < j). | Point out that converting the matrix to adjacency lists first is pointless: the input is already Θ(n²), so scanning the row is optimal. Offer union-find as the alternative, and note it also handles co |
| Graphs | Number of islands | BFS flood — queue per island, mark when pushed | O(m·n) | O(min(m, n)) queue | Checking grid[r][c] before the bounds check (index error). | Ask whether you may mutate the grid. If yes, overwrite visited land with '0' ('sink' it) and skip the visited array. If no, use visited. Mention that recursive DFS can reach depth m·n = 9·10⁴, so |
| Graphs | Flood fill algorithm | Recursive DFS — repaint, recurse on same-colour neighbours | O(m·n) | O(m·n) recursion | Missing the old == color guard, causing infinite recursion / stack overflow. | Raise the color == original case before the interviewer does. It is the whole trick of this question. |
| Graphs | Number of enclaves | Multi-source BFS from the border — flood from border land; count the rest | O(m·n) | O(m·n) | Seeding only the first and last row, forgetting the first and last column. | The same 'start from the boundary' move solves Surrounded Regions and Pacific Atlantic Water Flow. Name the pattern when you use it. |
| Graphs | Rotten Oranges | Multi-source BFS — queue all rotten at t = 0; process level by level | O(m·n) | O(m·n) | Looping while q without fresh > 0, which counts one extra minute for the final level that rots nothing. | Explain why one BFS from each rotten orange separately is wrong (or slow): the sources act at the same time. Seeding them all into one queue makes each fresh orange's BFS distance equal to its distanc |
| Graphs | Distance of nearest cell having one | Multi-source BFS — seed all 1s with distance 0 | O(m·n) | O(m·n) | BFS from each 0 separately: O((mn)²). | Without obstacles the distance is just the minimum Manhattan distance to a 1, which gives an O((mn)²) brute force. BFS still wins, and it keeps working when obstacles appear in a follow-up. The DP alt |
| Graphs | Surrounded Regions | Mark from the border — border O → '#', flood; then O→X, #→O | O(m·n) | O(m·n) stack | Flipping regions during the first scan, which can flip a region before discovering it reaches the border. | This is the same move as Number of Enclaves: turn 'is this region enclosed?' into 'what can be reached from the edge?'. Using a third symbol ('#') avoids allocating a visited matrix. |
| Graphs | Number of distinct islands | Relative coordinates — store (r − r0, c − c0) of every cell in DFS order | O(m·n) | O(m·n) | Using absolute coordinates, so equal shapes never match. | The interviewer wants to hear why the encoding is canonical: same anchor (first cell in scan order) plus a deterministic DFS order means equal shapes produce equal sequences. A path signature must als |
| Graphs | Detect a cycle in an undirected graph | DFS with parent — dfs(u, p): visited neighbour ≠ p ⇒ cycle | O(V + E) | O(V) | Checking only from node 0. | Mention the one-line alternative: a forest with V nodes and c components has exactly V − c edges, so a cycle exists iff E > V − c. Union-find gives the same answer: a cycle exists iff some edg |
| Graphs | Bipartite graph | BFS colouring — queue; neighbour gets the opposite colour | O(V + E) | O(V) | Colouring only the component of node 0. | State the theorem: bipartite ⇔ no odd-length cycle. A conflict found by BFS is direct evidence: the two same-coloured endpoints lie at equal depth, and their paths back to the common ancestor form an |
| Graphs | Topological sort or Kahn's algorithm | Kahn's algorithm (BFS on in-degrees) — queue of in-degree-0 nodes; decrement neighbours | O(V + E) | O(V) | DFS: appending u before the children (pre-order) instead of after. | Kahn's version detects cycles for free: if fewer than V nodes are output, the leftovers lie on or behind a cycle. It is also iterative and easy to adapt for 'lexicographically smallest order' (use a m |
| Graphs | Detect a cycle in a directed graph | Kahn's algorithm — cycle iff fewer than V nodes get processed | O(V + E) | O(V) | Using a single visited flag, which reports diamonds as cycles. | Draw the diamond to explain why the undirected parent trick fails here. Then offer both fixes: three colours (white/grey/black) or Kahn. Kahn is iterative and has no stack-depth risk. |
| Graphs | Find eventual safe states | Kahn on the reversed graph — reverse edges, peel out-degree-0 nodes | O(V + E) | O(V + E) | Treating 'some path reaches a terminal' as safe; the definition is every path. | LC 802 gives graph as adjacency lists; Striver's version uses V + adjacency. Both reduce to 'not on and not leading to a cycle'. Explaining the reverse-graph Kahn idea earns more credit than the D |
| Graphs | Course Schedule I | Kahn's algorithm — process in-degree 0 courses; all n processed? | O(V + E) | O(V + E) | Reversing the pair meaning (harmless for I, fatal for II). | Say 'this is cycle detection in a directed graph' immediately, then code Kahn. Either edge direction gives the right boolean, but Course Schedule II needs the correct one, so set it up properly here. |
| Graphs | Course Schedule II | Kahn's algorithm — pop in-degree-0 courses in order | O(V + E) | O(V + E) | Building a → b and outputting a reversed order. | Many valid orders exist; the checker accepts any of them. Explain why Kahn's order is valid: a course is popped only after its in-degree reaches 0, i.e. after every prerequisite has been popped. |
| Graphs | Alien dictionary | Adjacent pairs + Kahn — first mismatch of neighbours → edge; Kahn on k letters | O(N·L + k) | O(k²) | Adding an edge for every differing position, not just the first. | Three gotchas to raise out loud: (1) only adjacent pairs matter, since comparing all pairs adds only transitive edges; (2) only the first mismatch gives an edge; (3) the prefix case is invalid. Le |
| Graphs | Shortest path in DAG | Topological order + relaxation — Kahn order; relax out-edges once | O(V + E) | O(V + E) | Relaxing from unreachable nodes with INT_MAX + w (overflow). | Contrast this with Dijkstra: no heap, linear time, and it handles negative edges because the processing order is fixed by the topology, not by distances. With all signs flipped, the same code finds th |
| Graphs | Shortest path in undirected graph with unit weights | BFS — dist set at discovery is final | O(V + E) | O(V + E) | Updating dist on pop instead of discovery, so nodes are queued several times. | Say why BFS is correct (the queue holds at most two consecutive distance values, in order) and when it stops being correct: weighted edges need Dijkstra, and 0/1 weights need a deque (0-1 BFS). |
| Graphs | Word ladder I | BFS with on-the-fly neighbours — try 26 letters per position; remove from set when queued | O(N·L²·26) | O(N·L) | Marking visited on pop, so words are enqueued many times (TLE). | State the cost: O(N · L · 26) candidate generation, each costing O(L) to build and hash, so O(N · L² · 26). The all-pairs graph would be O(N² · L). Bidirectional BFS, expanding the smaller frontier ea |
| Graphs | Word ladder II | BFS depth map + backtracking — depth per word, then DFS back from end | O(N·L²·26 + paths·len) | O(N·L) | Removing a word from the set as soon as it is reached within a layer, which loses alternative same-layer parents. | The naïve 'BFS storing full paths in the queue' is what Striver codes first. It passes small inputs, but blows up in memory when many paths share prefixes. The depth-map + backtrack version is what LC |
| Graphs | Dijkstra's algorithm | Min-heap with lazy deletion — pop smallest (d, u); skip stale; relax | O((V + E) log V) | O(V + E) | Skipping the stale-entry check: still correct, but it re-relaxes edges and can degrade badly. | Name the variants and their costs: binary heap with lazy deletion O((V + E) log V), which is what everyone codes; the array scan O(V²), which is better for dense graphs (E ≈ V²); and std::set with e |
| Graphs | Print shortest path | Dijkstra with parent pointers — parent[v] = u on every improvement; walk back from n | O((n + m) log n) | O(n + m) | Setting parent when popping instead of when improving. | GfG's version prepends the path weight to the list. Mention it, but the reconstruction is the point. Parent pointers are always set on the improving relaxation, never on pop. |
| Graphs | Shortest distance in a binary maze | BFS — distance grid; first discovery is final | O(nm) | O(nm) | Allowing diagonal moves (LC 1091 allows 8 directions; this problem doesn't). | Ask: is the source itself guaranteed to be 1? Does src == dst return 0? Then say 'unit weights ⇒ BFS', and explain why Striver's Dijkstra framing collapses into a queue. |
| Graphs | Path with minimum effort | Dijkstra on max-step — heap of (effort, r, c); relax with max | O(nm log nm) | O(nm) | Summing differences instead of taking the max. | Offer three solutions and rank them: binary search on the answer + BFS feasibility (O(nm log H)), Dijkstra with max (O(nm log nm)), and union-find adding edges in increasing weight until the corners c |
| Graphs | Cheapest flights within K stops | Bellman-Ford with k + 1 rounds — relax every edge from the previous round's snapshot | O(k·E) | O(n) | Relaxing in place within a round, which lets one round use several flights. | Striver's solution is a BFS queue of (stops, node, cost) with a dist array, processed level by level, so stops increase monotonically. Bellman-Ford with a snapshot is the cleanest to prove. Both r |
| Graphs | Minimum multiplications to reach end | BFS over residues — dist array, −1 = unseen; return at discovery of end | O(10⁵· | arr | ) | O(10⁵) | Forgetting the mod when indexing dist. | The key move is recognising the implicit graph and bounding it: 10⁵ states × |arr| edges. Striver codes it with Dijkstra, but every edge weighs 1, so a plain BFS is enough. Ask whether start == end |
| Graphs | Number of ways to arrive at destination | Dijkstra with ways array — improve → ways[v] = ways[u]; tie → ways[v] += ways[u] | O(E log V) | O(V + E) | int distances (overflow). | Two traps to flag: distances overflow 32-bit (sums up to 2·10¹¹), so use long; and ties must add while improvements reset. Comparing floats or applying the mod to distances are both instant |
| Graphs | Bellman-Ford algorithm | Bellman-Ford (V − 1 rounds + check) — relax all edges V−1 times; one more improving pass ⇒ negative cycle | O(V·E) | O(V) | Relaxing from unreachable nodes (10⁸ + (−5) < 10⁸ looks like an improvement). | Say all three facts: V − 1 rounds suffice; a V-th improving round proves a negative cycle; and it works for directed graphs. An undirected negative edge is itself a 2-cycle. Mention the early-exit opt |
| Graphs | Floyd Warshall algorithm | Floyd-Warshall triple loop — for k: for i: for j: d[i][j] = min(d[i][j], d[i][k] + d[k][j]) | O(n³) | O(1) extra | Putting k in an inner loop, which gives wrong answers. | It handles negative edges, and detects negative cycles: some d[i][i] < 0 afterwards. Use it when n ≤ ~400 or when you need all pairs on a dense graph. Otherwise run Dijkstra from every node: O(V·E l |
| Graphs | Find the city with the smallest number of neighbors at a threshold distance | Floyd-Warshall + count — all-pairs matrix, then count per row | O(n³) | O(n²) | Tie-break with < while scanning upward (returns the smallest index). | Mention the alternative, n Dijkstra runs (O(n · E log n)), which is better for sparse large graphs; here Floyd is simpler. The tie-break is the bug magnet: iterate ascending with <=, or descending w |
| Graphs | Network delay time | Dijkstra — heap from k; answer = max dist | O(E log n) | O(n + E) | Including index 0 in the max (it stays ∞ in a 1-indexed array). | A 10-minute warm-up: say 'single-source shortest paths, take the max', code heap Dijkstra, and handle the 1-indexing. With n ≤ 100, mention that Bellman-Ford or Floyd also pass. |
| Graphs | Swim in rising water | Min-heap flood (Dijkstra) — always expand the lowest reachable cell; track the max so far | O(n² log n) | O(n²) | Starting the heap at time 0 instead of grid[0][0]. | Recognise it as the twin of Path With Minimum Effort. Three solutions again: binary search on t + DFS (O(n² log n²)), Dijkstra/min-heap 'flood' (O(n² log n)), and union-find, adding cells in elevati |
| Graphs | Disjoint Set (Union-Find) | Union by size + path compression — smaller root under larger; find flattens the path | O(α(n)) amortised | O(n) | Comparing parent[u] == parent[v] instead of find(u) == find(v). | Say the two optimisations by name and what each guarantees: union by size/rank keeps height O(log n) on its own; path compression on its own is O(log n) amortised; both together are O(α(n)). Write `fi |
| Graphs | Find the MST weight | Kruskal's algorithm — sort edges by weight; accept an edge if DSU says its ends differ | O(E log E) | O(V) | Prim: marking a vertex visited when pushed instead of when popped (that is Dijkstra-style relaxation and gives wrong totals without a key array). | Know both and say when each wins: Kruskal is shortest to code with a DSU and natural for an edge list (O(E log E)); Prim with a heap fits an adjacency list and dense graphs. If asked for the edges, no |
| Graphs | Number of operations to make network connected | DSU — union every cable; components = n − successful unions | O(n + E·α(n)) | O(n) | Counting spare edges and comparing with c − 1 (correct but redundant once E ≥ n − 1 is checked). | State the counting argument before coding: a connected graph on n nodes needs n − 1 edges, and a graph with c components and E ≥ n − 1 edges always has at least c − 1 redundant edges. Then it's one DS |
| Graphs | Accounts merge | DSU on account indices — email → first owner; union owners; group emails by root | O(N log N) | O(N) | Merging accounts by name. | The trap is merging by name. Say 'union account indices through an email → owner map', which keeps the DSU size at n accounts instead of all emails. Mention the DFS-on-email-graph alternative and that |
| Graphs | Number of islands II | Online DSU — new cell +1; each union with a distinct neighbour −1 | O(n·m + k·α) | O(n·m) | Not skipping repeated cells (count goes up by one wrongly). | Lead with the brute force (BFS after each op, O(k·nm)) to show you see why it's too slow, then the incremental argument. The most common bug is the repeated cell: say out loud that you skip it. |
| Graphs | Making a large island | DSU sizes + distinct neighbour roots — union all land; each 0 scores 1 + Σ distinct neighbour sizes | O(n²·α) | O(n²) | Summing neighbour sizes without deduping roots. | Say the two-pass plan up front: pass 1 builds island sizes, pass 2 evaluates each 0 in O(1). The two must-mention details are the distinct-root set and the all-ones case. DFS labelling is equally fine |
| Graphs | Most stones removed with same row or column | DSU on row and column nodes — union(row x, col y + OFFSET) per stone; count roots among used nodes | O(n·α) | O(R + C) | Offset too small, so row 5 and column 5 become the same node. | The interviewer wants the reduction: prove that a component of size s loses exactly s − 1 stones (remove in reverse BFS order from any root, never the last). Then present the row/column-node trick to |
| Graphs | Kosaraju's algorithm | Kosaraju (two DFS passes) — DFS for finish order; DFS on reversed graph in reverse finish order | O(V + E) | O(V + E) | Pass 2 on the original graph (leaks into downstream SCCs). | Explain why the finish order matters before writing it: the condensation is a DAG, finish order is a topological order of it, and reversing edges flips sources into sinks so DFS can't leak. Bridges / |
| Graphs | Bridges in graph | Tarjan tin / low — DFS; low[u] = min(tin[u], low[child], tin[back-edge target]); bridge if low[v] > tin[u] | O(V + E) | O(V + E) | Using >= (that's the articulation-point condition). | Define tin and low precisely and state the bridge condition before coding. Bridges / articulation points / SCC are rare at L3/L4 (the repo marks Tarjan/SCC out of scope); know the idea, the invari |
| Graphs | Articulation point in graph | Tarjan tin / low — non-root: low[child] ≥ tin[u]; root: ≥ 2 children | O(V + E) | O(V + E) | Using > (bridge condition), which misses vertices on cycles joined at a point. | Contrast with bridges explicitly: ≥ instead of >, and the root special case. Bridges / articulation points / SCC are rare at L3/L4 (the repo marks Tarjan/SCC out of scope); know the idea, the inva |
| Dynamic programming | Climbing stairs | Tabulation with two variables — iterate bottom-up keeping prev2, prev1 | O(n) | O(1) | Base case f(0) = 0, which makes every answer wrong. | This is the template for the whole DP part, so narrate all four stages: recurrence → memoization → tabulation → space optimisation. Interviewers often extend it to steps {1, 2, …, k} or forbidden st |
| Dynamic programming | Frog Jump | Tabulation, O(1) space — keep dp[i−1], dp[i−2] only | O(n) | O(1) | Greedy next-cheaper-jump. | Show a counter-example to greedy before writing the DP: [30, 10, 60, 10, 60, 50]. Greedy picks the cheaper next jump each time and pays 60, while the optimum is 40. |
| Dynamic programming | Frog jump with K distances | Tabulation — fill dp left to right | O(n·k) | O(n) | Looping j past i (a negative index wraps around silently in Python). | State the complexity honestly as O(n·k). If asked to speed it up, note that |h[i] − h[j]| depends on i, so a monotonic deque does not apply directly. Splitting into h[j] ≥ h[i] and h[j] < h[i] |
| Dynamic programming | Maximum sum of non adjacent elements | Space-optimised tabulation — prev = dp[i−1], prev2 = dp[i−2] | O(n) | O(1) | Base case f(−1) returning a[0] instead of 0. | Write the pick/not-pick recursion first and let the interviewer watch it turn into a two-variable loop. This exact recurrence returns in House Robber II, in the knapsack family and in stock DP. |
| Dynamic programming | House robber | Two passes by index range — same, without copying | O(n) | O(1) | Forgetting n = 1, which returns 0. | Say the reduction in one sentence before coding: "Either the first house is excluded or the last one is." Handle n = 1 explicitly, because both slices would otherwise be empty. |
| Dynamic programming | Ninja's training | Tabulation with one row — prev[t] = best ending with t yesterday | O(n·9) | O(1) | Greedy max each day, which can forbid a bigger value tomorrow. | The lesson here is that when a choice constrains the next one, you add the previous choice to the state. Say "state = (day, last activity)" out loud. The rest is the familiar 1D pattern. |
| Dynamic programming | Grid unique paths | 1D rolling row — row[j] += row[j−1] | O(m·n) | O(n) | Computing (m+n−2)! / … directly, which overflows. | Write the DP, then mention the O(min(m, n)) combinatorial answer. Compute it multiplicatively (res = res·(N−k+i)/i) so every intermediate value stays an integer. |
| Dynamic programming | Unique paths II | 1D rolling row — row[j] = 0 if blocked else row[j] + row[j−1] | O(m·n) | O(n) | Pre-filling row 0 and column 0 with 1. | Don't pre-fill the first row and column with 1s. A single obstacle in row 0 blocks everything to its right. Let the general recurrence handle the borders. |
| Dynamic programming | Minimum Falling Path Sum | Row-by-row tabulation — prev row → cur row | O(n²) | O(n) | Starting only from column 0 (the path may start anywhere). | Values can be negative, so don't use 0 as an "unset" sentinel. Out-of-range neighbours must be ∞, not 0. The maximum-falling-path version only flips min to max and ∞ to −∞. |
| Dynamic programming | Triangle | Bottom-up with one row — dp = last row; move up | O(n²) | O(n) | Greedy smaller child at each step. | This is the canonical "fixed start, variable end → reverse the direction" trick. The top-down version needs min of the last row plus edge checks, while bottom-up has neither. Mention the follow-up o |
| Dynamic programming | Cherry pickup II | Bottom-up with a 2D layer — front[c1][c2] from the row below | O(R·C²·9) | O(C²) | Counting a shared cell twice. | Explain why the state is 3D: "Both robots advance one row per step, so a single row index describes both." This is the same trick as Cherry Pickup I, where r1 + c1 = r2 + c2 collapses one coordinate |
| Dynamic programming | Count Square Submatrices with All Ones | DP on the bottom-right corner — dp = 1 + min(up, left, diag); sum dp | O(m·n) | O(m·n) | Using max instead of min of the three neighbours. | Prove the recurrence. A side-s square at (i, j) needs side-(s−1) squares ending at the top, left and top-left neighbours, and the smallest of those three limits s. The same DP gives the Maxima |
| Dynamic programming | Best time to buy and sell stock | Running minimum — profit = price − min so far | O(n) | O(1) | Returning max − min overall (the max may come before the min). | State the invariant: "mini is the cheapest price strictly before today." Update the profit before updating mini, or update mini first; both work here because selling the same day gives 0. |
| Dynamic programming | Best time to buy and sell stock II | Tabulated state machine, O(1) — aheadBuy, aheadSell rolled backward | O(n) | O(1) | Updating aheadBuy before computing curSell from the old value (use temporaries). | Code the state machine even though the greedy is shorter. It extends directly to cooldown, fees and k transactions, and the interviewer will usually ask for one of those next. |
| Dynamic programming | Best time to buy and sell stock III | Four forward variables — buy1, sell1, buy2, sell2 | O(n) | O(1) | Decrementing the cap on buy and on sell. | Present the 3D memo first, then show the four-variable forward version and explain each: buy1 = best cash after the first buy, sell1 = after the first sell, and so on. Each one feeds the next on t |
| Dynamic programming | Best time to buy and sell stock IV | Forward buy[]/sell[] arrays — k copies of the Stock III chain | O(n·k) | O(k) | Allocating n × k memory when k is huge without the shortcut. | Mention the k ≥ n/2 → unlimited shortcut. It turns an O(n·k) DP into O(n) when k is huge (e.g. 10⁹), and older versions of this problem test it. |
| Dynamic programming | Best time to buy and sell stock with transaction fees | Forward hold / cash — cash = max(cash, hold + p − fee) | O(n) | O(1) | Charging the fee on both buy and sell. | Say that the fee is charged once per transaction: "I'll subtract it at sell time." This is a one-line change to Stock II, which is the point of learning the state machine. |
| Dynamic programming | Best time to buy and sell stock with cooldown | Backward tabulation with two look-ahead rows — front1, front2 | O(n) | O(1) | Applying the cooldown after a buy instead of after a sell. | Show the one-line change from Stock II (i + 1 → i + 2 on sell). Mention the alternative three-state forward machine (hold, sold, rest), which some interviewers prefer. |
| Dynamic programming | Subset sum equals to target | 1D tabulation, t descending — dp[t] | = dp[t − x] | O(n·k) | O(k) | Iterating t upward in 1D, which reuses an item (that gives unbounded subset sum). | This is the parent of every knapsack-style problem in this section. Say "state = (index, remaining target), pick/not-pick" and draw the table. The 1D trick (iterate t from high to low) is what inter |
| Dynamic programming | Partition equal subset sum | 1D boolean DP — dp[t] | = dp[t − x], t descending | O(n·S) | O(S) | Missing the odd-total check. | Lead with the reduction and the parity check; that is the whole insight. Then reuse the 1D boolean subset-sum loop. |
| Dynamic programming | Partition a set into two subsets with minimum absolute sum difference | Boolean row + scan — dp[t] for t ≤ S/2, take the largest true | O(n·S) | O(S) | Scanning all t up to S without the ≤ S/2 restriction (fine, but return |S − 2t|). | Point out the restriction: the DP needs non-negative values with a small total. For LC 2035 (negatives, n ≤ 30) say "meet in the middle" and don't try to force this table. |
| Dynamic programming | Count subsets with sum K | 1D counting DP — dp[t] += dp[t − x], t descending | O(n·k) | O(k) | Returning 1 as soon as t == 0, which ignores zeros left to process. | Say up front how zeros are handled. The classic bug is if t == 0: return 1 before checking the remaining elements, which undercounts subsets that include zeros. |
| Dynamic programming | Count partitions with given difference | 1D counting DP — findWays(arr, (S+d)/2) | O(n·S) | O(S) | Targeting (S − d)/2 vs (S + d)/2: both give the same count (complements), but don't mix them. | Write the two equations on the board and solve them. The interviewer is checking that you see the reduction, not that you invent a new DP. |
| Dynamic programming | 0 and 1 Knapsack | 1D tabulation, w descending — dp[w] = max(dp[w], v + dp[w − wt]) | O(n·W) | O(W) | Ascending w (turns into unbounded knapsack). | Show the ratio-greedy counter-example, then write the 2D recurrence and collapse it. Explain the descending loop: "dp[w − wt] must still be the value without this item." |
| Dynamic programming | Minimum coins | 1D tabulation, target ascending — dp[t] = min(dp[t], 1 + dp[t − c]) | O(n·amount) | O(amount) | Greedy by largest coin. | Contrast 0/1 vs unbounded in one line: "take → stay at i" in the 2D form, or "loop the target upward" in the 1D form. Use amount + 1 as infinity to avoid overflow on 1 + INF. |
| Dynamic programming | Target sum | Count subsets with sum (S + target)/2 — reduction + 1D counting | O(n·S) | O(S) | Missing the parity / range check, which reads a negative index. | Brute force is 2ⁿ (fine for n ≤ 20, so say so). Then show the reduction. Handle a negative target with abs(target): by symmetry the count is the same. |
| Dynamic programming | Coin change II | 1D tabulation, coins outer — dp[t] += dp[t − c], t ascending | O(n·amount) | O(amount) | Amount loop outside, which counts permutations. | Expect the question "Why is this combinations and not permutations?" Answer: the outer loop over coins means every combination is built in coin-index order, exactly once. |
| Dynamic programming | Unbounded knapsack | 1D tabulation, capacity ascending — dp[w] = max(dp[w], v + dp[w − wt]) | O(n·W) | O(W) | Descending loop (that gives 0/1). | Put 0/1 and unbounded side by side and point at the one changed loop bound. That contrast is the takeaway of this group. |
| Dynamic programming | Rod cutting problem | Unbounded knapsack table — items = lengths, capacity = n | O(n²) | O(n) | Off-by-one between length L and price[L−1]. | Say the mapping explicitly: "length = weight, price = value, rod length = capacity, unlimited pieces → unbounded knapsack." Recognising reductions is the skill being tested here. |
| Dynamic programming | Longest increasing subsequence | Tails + binary search — lower_bound replace or append | O(n log n) | O(n) | upper_bound for a strict LIS (lets equal values chain). | Give the O(n²) DP with its state sentence, then offer the O(n log n) version. Explain why overwriting is safe: a smaller tail for the same length can only help future elements. Use lower_bound for s |
| Dynamic programming | Print longest increasing subsequence | dp + parent array — parent[i] = best predecessor | O(n²) | O(n) | Following parents from n − 1 instead of from argmax dp. | Ask whether any LIS is fine or a specific one (lexicographically smallest, first-occurring). The parent array works for either with a tie rule. For O(n log n) reconstruction, store for each tail slot |
| Dynamic programming | Largest divisible subset | Sort + LIS-style dp + parent — dp[i] = 1 + max dp[j] with a[i] % a[j] == 0 | O(n²) | O(n) | Not sorting (then adjacency checks are insufficient). | Justify the sort: after sorting, "pairwise divisible" collapses to "each divides the next" because of transitivity. Then it is the print-LIS code with one changed comparison. |
| Dynamic programming | Longest string chain | Sort + hash of deletions — dp[w] = 1 + max dp[w without char i] | O(n·L²) | O(n·L) | Not sorting by length (predecessors may appear later). | Present both. The LIS + isPredecessor form is O(n²·L) and reuses LIS directly. The hash-of-deletions form is O(n·L²) and better when n is large. Mention that sorting by length makes every predecesso |
| Dynamic programming | Longest bitonic subsequence | Two O(n²) LIS passes — front[i] + back[i] − 1 | O(n²) | O(n) | Forgetting the − 1 (the peak is counted twice). | Clarify whether a monotone sequence counts. The two-pass LIS trick also solves "minimum removals to make a mountain array" (LC 1671) as n − max bitonic with both sides required. |
| Dynamic programming | Number of longest increasing subsequences | dp + cnt arrays — reset on longer, add on equal | O(n²) | O(n) | cnt[i] += cnt[j] on a strict improvement (must reset). | State both arrays and the reset-vs-add rule clearly. The common bug is adding when the length strictly improves. |
| Dynamic programming | Longest common subsequence | Two-row tabulation — prev / cur rows over prefixes | O(n·m) | O(m) | Off-by-one between dp index i and character a[i−1]. | Write the 1-indexed recurrence with the empty-prefix base row. Then reduce space to two rows. Interviewers often ask you to print the LCS; walk back from dp[n][m]. |
| Dynamic programming | Longest common substring | Ending-at DP, two rows — match → diag + 1, else 0; track max | O(n·m) | O(m) | Returning dp[n][m]. | Contrast with LCS in one sentence: "Mismatch resets to 0 instead of taking a max, and I track a global max." Mention suffix automaton / binary search + hashing for O((n+m) log) if asked about scale. |
| Dynamic programming | Longest palindromic subsequence | LCS(s, reverse(s)), two rows — reuse LCS | O(n²) | O(n) | Confusing this with the longest palindromic substring (LC 5, expand-around-centre). | Lead with the reduction to LCS (one line, reuses code). Then show the interval version, which generalises to palindromic-substring problems and partitioning. |
| Dynamic programming | Minimum insertions to make string palindrome | n − LCS(s, reverse(s)) — reuse LPS | O(n²) | O(n) | Returning LPS instead of n − LPS. | Argue both directions: "n − LPS insertions suffice (mirror the rest), and fewer is impossible, because the final palindrome's restriction to the original characters is a palindromic subsequence." Th |
| Dynamic programming | Shortest common supersequence | LCS table + backward walk — match → emit once, else emit the dropped char | O(n·m) | O(n·m) | Emitting the character of the side you move toward instead of the one you leave. | State the length formula first, then reconstruct. The key detail is that on a non-match you emit the character you leave behind (a[i−1] when moving up, b[j−1] when moving left). |
| Dynamic programming | Distinct subsequences | 1D DP, j descending — dp[j] += dp[j−1] on match | O(n·m) | O(m) | Ascending j in 1D (reuses the same s character twice). | Spell out the base cases: t empty → 1; s empty with non-empty t → 0. Overflow: intermediate cells can exceed 32 bits even though the final answer doesn't. Unsigned 64-bit arithmetic wraps mod 2⁶ |
| Dynamic programming | Edit distance | Two-row tabulation — prev / cur with cur[0] = i | O(n·m) | O(m) | Base row/column set to 0. | Name each transition as an operation; interviewers check that you know which neighbour means what. The bases are i and j, not 0. With two rows, cur[0] = i must be set for each row. |
| Dynamic programming | Wildcard matching | Two-row tabulation — prev = pattern row i−1 | O(n·m) | O(m) | * handled as "match exactly one". | Explain the * transition as "either it's done (empty) or it eats one more character and stays." That two-way choice keeps the DP O(n·m) instead of looping over every length. A greedy two-pointer wit |
| Dynamic programming | Word break | Prefix DP with hash set — dp[i] | = dp[j] ∧ s[j..i) ∈ set | O(n·L²) | O(n + D·L) | Unmemoised recursion (exponential). | Plain recursion is exponential on inputs like "aaaa…ab" with ["a","aa",…]. Memoise on the start index. Mention the trie-based inner loop if the dictionary is large. |
| Dynamic programming | Count palindromic subsequences | Bottom-up interval table — i descending, j ascending | O(n²) | O(n²) | Negative values after subtraction under a modulus. | Derive the formula with a Venn diagram: "without s[i]" plus "without s[j]" double-counts "without both". When the ends match, the extra term is every inner palindrome wrapped plus the pair itself. |
| Dynamic programming | Matrix chain multiplication | Bottom-up interval table — i from n−1 down, j from i+1 up | O(n³) | O(n²) | Indexing matrices from 0 and getting arr[i−1] wrong. | Say the four partition-DP steps: (1) state f(i, j) over a contiguous block, (2) base case for a single item, (3) loop k over every split, (4) combine as cost(split) + f(left) + f(right). Tabulate |
| Dynamic programming | Minimum cost to cut the stick | Bottom-up interval table — by increasing gap j − i | O(m³) | O(m²) | DP over positions 0..n (n up to 10⁶): use cut indices. | Explain why sorting is needed: after sorting, the cuts inside a piece form a contiguous index range, so the state is two indices. Without sorting, the subproblems are not independent intervals. |
| Dynamic programming | Burst balloons | Bottom-up interval table — i descending, j ascending | O(n³) | O(n²) | Choosing the first balloon to burst (the subproblems aren't independent). | The decisive line is: "I pick the last balloon in the range, because then its neighbours are known." Pad with 1 on both ends. This is the classic reversal trick for partition DP. |
| Dynamic programming | Evaluate boolean expression to true | Bottom-up T / F tables — i descending over symbols, j ascending | O(n³) | O(n²) | Tracking only the true count. | Lead with "I need both the true and false counts per interval, because XOR and OR depend on the false side." Splits are only at odd indices. The state can be (i, j, wantTrue), as in Striver, or a pa |
| Dynamic programming | Palindrome partitioning II | Front partition + isPal table — O(1) palindrome lookups | O(n²) | O(n²) | Returning pieces instead of cuts (off by one). | Note that the MCM-style O(n³) f(i, j) works but is too slow for n = 2000. The front-partition view ("where does the first piece end?") is the intended solution. Build the palindrome table with `isPa |
| Dynamic programming | Partition array for maximum sum | Bottom-up suffix dp — i from n−1 down | O(n·k) | O(n) | Recomputing the block max with an inner scan (O(n·k²)). | It is the same shape as palindrome partitioning II: choose where the first block ends. State the running-max optimisation. A backward or forward fill is fine; forward dp[i] = best for the prefix of |
| Dynamic programming | Minimum path sum in a grid | 1D rolling DP — row[j] = g[i][j] + min(row[j], row[j-1]) | O(mn) | O(n) | Treating out-of-grid neighbours as 0 instead of +∞ in the recursion. | Follow the DP ladder: |
| Tries | Implement Trie (prefix tree) | Trie of child arrays — node = children[26] + end flag | O(L) per op | O(total chars · 26) | Returning true from search just because the path exists (forgetting end). | Draw the node first: children[26] + end. Then write a shared walk(s) helper that returns the last node or null. search = walk(w) && walk(w).end, startsWith = walk(p) != null. Mention the arr |
| Tries | Implement Trie II (count and erase) | Trie with pass / end counters — pass++ along the path, end++ at the last node | O(L) per op | O(total chars · 26) | Incrementing pass on the root (then the root's pass is the total count, which is harmless, but off-by-one if you read it as a prefix). | The interviewer wants the pass counter. Without it, prefix counting needs a DFS over the subtree. With it, every op is O(L). Ask whether to free nodes whose pass drops to 0 (optional, and it saves |
| Tries | Longest word with all prefixes (complete string) | Trie: every node on the path is an end — insert all, then walk each word checking end | O(Σ L) | O(Σ L · 26) | Only checking end at the last node (that is just search). | State that a single-letter word is complete if it is in the list (its only prefix is itself). Then: build the trie, check each word, keep the best by (length desc, lexicographic asc). A sort + hash-se |
| Tries | Number of distinct substrings in a string | Suffix trie, count new nodes — for each start i, walk/extend from root | O(n²) | O(n² · 26) worst | Forgetting the + 1 for the empty string, or adding it when the problem doesn't want it. | Confirm whether the empty string counts (the GfG/Striver version does; many others don't). The trie approach is O(n²) time and nodes. Mention suffix arrays/automata (O(n) or O(n log n)) as the scalabl |
| Tries | Maximum XOR of two numbers in an array | Binary trie, greedy from MSB — insert bits 30..0; query takes the opposite bit when it exists | O(31·n) | O(31·n) | Walking bits LSB first (the greedy only works MSB first). | Explain the greedy exchange argument: once you can set bit b, nothing in bits < b can make up for losing it (2^b > 2^b − 1). Then show the binary trie. The 31-bit width is fixed, so this is O(31 |
| Tries | Maximum XOR with an element from the array | Offline sort + binary trie sweep — sort queries by m; insert nums ≤ m before answering | O((n + q) log + 31(n + q)) | O(31·n) | Answering in sorted order and returning that order. | Say offline early: queries can be reordered as long as the answers go back to their original indices. Sort queries by m with their index, sweep a pointer over sorted nums, then run the max-XOR |
| Strings advanced | Reverse every word in a string | Scan from the right — find each word's [j+1, i] going leftwards | O(n) | O(n) output (O(1) extra in-place in C++) | Splitting on ' ' (Python split(' '), Java split(" ")), which keeps empty tokens. | Ask whether extra spaces must be collapsed (yes here). Start with split + reverse + join to show you know the library route, then offer the O(1)-extra in-place version (C++ string is mutable): r |
| Strings advanced | Minimum number of bracket reversals to balance an expression | Two counters — open = unmatched '{', close = unmatched '}' | O(n) | O(1) | Missing the odd-length check. | Say the odd-length check first. Then explain why matched pairs can be removed safely (flipping inside a matched pair never helps), and derive ⌈c/2⌉ + ⌈o/2⌉ from the }}}{{{ shape. Note that c and |
| Strings advanced | Count and say | Iterative run-length encoding — repeat the encode step n − 1 times | O(Σ term lengths) | O(term length) | Forgetting to emit the final run. | Write the run-length step as a helper and loop it. The only real bug risk is the last run: either flush it after the loop or use the inner-while form below, which has no flush. Use a builder, not st |
| Strings advanced | Rabin-Karp algorithm | Rabin-Karp rolling hash — O(1) window hash update + verify on match | O(n + m) expected, O(n·m) worst | O(1) extra | Negative hash after the subtraction (C++/Java % keeps the sign). | Define the hash h(s) = Σ s[i]·B^(m−1−i) mod M, then derive the roll in one line. Mention: (1) keep values non-negative after subtracting (+ M); (2) verify on a hash hit, so the worst case is O(nm) |
| Strings advanced | Z-function | Linear Z-algorithm — reuse the Z-box [l, r) | O(n + m) | O(n + m) | Separator that can appear in the input. | Define z[i], draw the Z-box [l, r), and explain the two cases: i ≥ r (compare from scratch) and i < r (copy z[i − l], capped at r − i, then extend). The separator stops a match from runnin |
| Strings advanced | KMP algorithm (LPS array) | Prefix function with fallback — extend or follow lps[len − 1] | O(n) | O(n) | Using if instead of while for the fallback. | State the definition with proper prefix (not the whole string). Show the fallback chain len → lps[len−1] as 'the next-longest border of the current border'. Then: KMP search = LPS of pat, then |
| Strings advanced | Shortest palindrome | KMP on s#rev(s) — k = lps[-1] = longest palindromic prefix | O(n) | O(n) | Omitting the separator, so the border can be longer than s (e.g. aaaa). | Reduce first: 'prepend the minimum' ⇔ 'find the longest palindromic prefix'. Brute force checks each prefix (O(n²)). Then the trick: a prefix P is a palindrome iff P == rev(P), and rev(P) is a s |
| Strings advanced | Longest happy prefix | Prefix function — answer = s[:lps[n − 1]] | O(n) | O(n) | Returning s itself (the border must be proper). | Recognise it as the definition of the border, so lps[n − 1]. If you can't recall KMP under pressure, rolling hashes are the fallback: maintain the hash of s[:k] growing left-to-right and the hash |
| Maths | Print all primes till N | Sieve of Eratosthenes — cross out multiples from i², i up to √n | O(n log log n) | O(n) | Treating 1 as prime. | Start with trial division up to √x per number, O(n√n). Then the sieve: explain both optimisations (outer loop to √n, inner loop from i²) and quote O(n log log n) time and O(n) memory. For n ne |
| Maths | Prime factorisation of a number | SPF sieve + repeated division — spf[x] then x /= spf[x] | O(X log log X + Σ log x) | O(X) | Overwriting spf[j] with a larger prime (check spf[j] == j first). | One query: trial division to √x, O(√x). Many queries with a bounded value: SPF sieve once, then O(log x) each. State the crossover: q·√X vs X log log X + q log X. Mention that a leftover x > 1 |
| Maths | Count primes in range L to R | Sieve + prefix counts — pre[R] − pre[L − 1] | O(R log log R + q) | O(R) | pre[R] − pre[L], which drops L itself. | Per query, a sieve on [L, R] costs O(R) each. Precomputing once makes every query O(1). Get the L − 1 index right (pre[0] = 0). For R up to 10⁹ with a short range, switch to a segmented sieve. |
Check yourself 2 questions
What does each problem entry give?
Show answer
Best approach, complexity, the common mistake and what to say in the interview.
How do you narrow the bank?
Show answer
Filter by topic or search by name or technique.
Takeaway A filterable bank of 434 problems with approach, complexity, the common mistake and what to say.
16Python essentials & complexity
Coding/00-start-here/L3_CHEATSHEET.md, striver-a2z Part 1–2
Python essentials#
from collections import Counter, defaultdict, deque import heapq, bisect heapq.heappush(h,(-v,k)) # max-heap via negation bisect.bisect_left(a,x) # lower_bound from functools import cache # @cache memo sorted(a, key=lambda x:(x[1],-x[0])) float('inf'); divmod(a,b); a[::-1] sys.setrecursionlimit(10**6)
| Structure | Ops |
|---|---|
| list | append/pop end O(1); insert/pop(0) O(n) |
| deque | both ends O(1) |
| dict/set | avg O(1) |
| heapq | push/pop O(log n), heapify O(n) |
| sorted + bisect | search O(log n), insert O(n) |
Check yourself 2 questions
Max-heap in Python?
Show answer
Push negated values into heapq.
lower_bound in Python?
Show answer
bisect.bisect_left.
Takeaway Counter, defaultdict, deque, heapq (negate for max-heap), bisect and functools.cache cover most needs.
Big-O reference#
| Algorithm | Time | Space |
|---|---|---|
| Sort (Tim/merge) | n log n | n |
| Quick sort | n log n avg, n² worst | log n |
| Heap sort | n log n | 1 |
| Counting / radix | n+k | k |
| BFS / DFS | V+E | V |
| Dijkstra (heap) | (V+E) log V | V |
| Bellman-Ford | VE | V |
| Floyd | V³ | V² |
| Kruskal | E log E | V |
| Topo | V+E | V |
| Trie insert/search | L | ΣL |
| Subsets / perms | 2^n·n / n!·n | n |
Check yourself 2 questions
Quick sort worst case?
Show answer
O(n²).
Bellman-Ford complexity?
Show answer
O(V·E).
Takeaway Sorts are n log n, BFS/DFS V + E, Dijkstra (V + E) log V, Bellman-Ford VE.
17Last-minute checklist
Last-minute revision (one line each)#
- Read constraints first → pick target complexity from the N table
- Name the pattern out loud; give brute force then optimise
- Prefix-map seeds: longest {0:-1}, count {0:1}
- Exactly K = atMost(K) − atMost(K−1)
- Binary search on answer for min-max / max-min
- Monotonic stack for next greater/smaller; contribution technique for sums of mins
- Tree DP: return one arm, update global with both
- Knapsack 1D: 0/1 descending, unbounded ascending
- Russian doll: sort w asc, h desc, then LIS
- Burst balloons: choose the LAST balloon
- Dry-run on edge cases: empty, one element, all same, negatives, overflow
Check yourself 2 questions
Prefix-map seeds: longest versus count?
Show answer
Longest uses {0: −1}; count uses {0: 1}.
Exactly K distinct?
Show answer
atMost(K) − atMost(K−1).
Takeaway Constraints first, name the pattern, brute then optimise, and remember the small seeds and tricks.