CSCheatsheets
Coding interviews

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.

18sections
127cards
32diagrams
0%known

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.

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 dec

Before coding, state the invariant or DP state, prove why the next step is safe, then check complexity against the constraints.

Check yourself 2 questions
  1. Position, pair or rank question on sorted input: which family?

    Show answer

    Binary search or two pointers.

  2. 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 dec
Check yourself 2 questions
  1. Static range sums: which structure?

    Show answer

    Prefix sums, O(1) per query.

  2. 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#

FamilyPatterns covered hereJump
Arrays & searchHashing, prefix/suffix, two pointers, windows, binary search, sorting, selection, intervals§03 · §04 · §06
Linear structuresLinked-list pointers, stack/queue, monotonic stack/deque, heap§03 · §06
Trees & connectivityTraversals, BST, LCA, tree DP, trie, DSU§03 · §07
GraphsBFS/DFS, cycles, topo/DAG, shortest paths, MST, SCC, bridges, articulation points§08
Choices & optimizationGreedy, recursion, backtracking, pruning, DP state families§11 · §12 · §09
Strings, bits & mathTries, KMP, Z, rolling hash, palindromes, bit tricks, sieve and number theory§03 · §07
Range data structuresFenwick/BIT and advanced structure triggers§13 · §0 range route
Check yourself 2 questions
  1. Which families sit under arrays and search?

    Show answer

    Hashing, prefix/suffix, two pointers, windows, binary search, sorting, selection, intervals.

  2. 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#

SignalTechnique familyRecognition rule
Range queries plus updatesFenwick, segment tree, lazy propagation, sparse tableChoose by update type and whether the operation is associative/idempotent; see the range route above.
Ranks, kth value, or many distinct valuesCoordinate compression + Fenwick/order-statistics structureMap values to dense ranks, then maintain counts or prefix frequencies.
Offline range queriesMo's algorithm, sweep line, divide-and-conquerUse when queries can be reordered and moving a range boundary is cheap.
Many patterns in one textAho–CorasickTrie of patterns + failure links; scan the text once.
Many suffix or substring comparisonsSuffix array + LCP, suffix automatonUse when repeated substring queries outgrow rolling hash or a suffix trie.
Shortest paths with special structureDAG relaxation, 0–1 BFS, bidirectional BFS, A*Exploit acyclicity, binary weights, two endpoints, or a useful heuristic.
Network flow / one-to-one matchingMax flow (Dinic), bipartite matchingModel capacities or alternating paths; min cut gives a certificate.
Large choice set with n around 40Meet in the middleSplit the choices, enumerate each half, then combine sorted sums or states.
One answer for every root / digit constraintsRerooting DP / digit DPChoose a state that summarizes what a parent or prefix contributes.
Geometric ordering / hull / random streamSweep line, convex hull, reservoir samplingSort events or points by a coordinate; use randomized sampling when a stream cannot be stored.
Check yourself 2 questions
  1. Range queries plus updates suggest which family?

    Show answer

    Fenwick, segment tree with lazy propagation, or sparse table.

  2. 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
  1. What should you name before optimising?

    Show answer

    The brute-force route.

  2. 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#

MinDo
0–5Clarify: input size, sorted?, negatives?, duplicates?, empty? return format
5–15Brute force → say Big-O → optimise; name the pattern aloud
15–35Code clean; helper fns; meaningful names
35–45Dry-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
  1. What happens in the first 5 minutes?

    Show answer

    Clarify: input size, sortedness, negatives, duplicates, empty input, return format.

  2. 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#

NTargetTypical
≤10O(N!)permutations, brute backtracking
≤20O(2^N)subsets, bitmask DP
≤500O(N³)Floyd, interval DP
≤2000O(N²)2D DP, pairs
≤10^5O(N log N)sort, heap, binary search
10^5–10^6O(N)two-pointer, hash, sliding window
≥10^9O(log N)binary search on answer, math
Check yourself 2 questions
  1. N ≤ 10^5: target complexity?

    Show answer

    O(N log N).

  2. 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<=hi vs lo<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
  1. Name two advanced graph topics.

    Show answer

    Any two of: DAG paths, SCCs, bridges and cut vertices, matching, max flow.

  2. 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#

T(n) = a·T(n/b) + f(n) compare f(n) with n^(log_b a)f smaller → Θ(n^(log_b a))f equal → Θ(n^(log_b a) · log n)f larger → Θ(f(n))2T(n/2) + O(1) → Θ(n) tree traversal2T(n/2) + O(n) → Θ(n log n) merge sortT(n/2) + O(1) → Θ(log n) binary searchT(n−1) + T(n−2) → Θ(φⁿ) naive Fibonacci
  • 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
  1. T(n) = 2T(n/2) + O(n)?

    Show answer

    Θ(n log n).

  2. 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/targetTwo pointers / binary search
contiguous subarray/substring, longest/shortestSliding window (positives only!)
subarray sum = k, negatives allowedPrefix sum + hashmap {0:1}
top-K / K-th / stream medianHeap (size K) / two heaps
next greater / smaller, span, histogramMonotonic stack
min/max that satisfies conditionBinary search on answer
all combinations / permutations / subsetsBacktracking
shortest path unweighted / gridBFS (0-1 BFS if weights 0/1)
weighted shortest pathDijkstra (non-neg) / Bellman-Ford (neg)
dependencies / orderTopo sort (Kahn)
connected groups, dynamic mergingUnion-Find
overlapping intervalsSort by start, merge / sweep
prefix strings / word dictionaryTrie
count ways / min cost / max value with choicesDP
linked list cycle / middleFast & slow pointers
max XOR pairBit trie
Check yourself 2 questions
  1. Subarray sum = k with negatives allowed?

    Show answer

    Prefix sums with a hash map.

  2. 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 dec
Check yourself 2 questions
  1. Contiguous range with only positive values?

    Show answer

    Sliding window.

  2. 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#

Array problem
1Sorted, or sorting is allowed?
yes
Two pointers2-sum sorted, 3-sum, 4-sum, merge, union/intersection
no
2Contiguous subarray?
max sum
Kadanemax subarray, max product (track min too)
sum = k, with negatives
Prefix sum + hash mapcount / longest subarray sum k, XOR k
sum = k, all positive
Sliding windowlongest subarray sum ≤ k
no
3Rearrange in place?
few distinct values
Dutch national flagsort 0s 1s 2s
move / rotate
Write pointer or reversal trickzeroes to end, rotate by k, next permutation
no
4Element appearing > n/k times?
yes
Boyer–Moore votingk − 1 candidates, then verify
no
5Count pairs i ‹ j with a condition?
yes
Merge-sort countinginversions, reverse pairs
no
Math / XOR identitiesmissing number, missing and repeating
Check yourself 2 questions
  1. Maximum subarray sum?

    Show answer

    Kadane's algorithm.

  2. 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#

1Contiguous subarray / substring?
no
not a window:sort + two pointers, DP, prefix sums
yes
2Window size given?
yes, k
fixed window:add a[r], drop a[r-k]
no
3Is validity monotone? (valid window ⇒ every sub-window valid)
no (negatives, exact sums)
prefix sums + hashmap
yes
4Asked for?
longest
expand r; shrink while invalid;best = max(len)
shortest
expand r until valid;shrink while still valid, record
count ≤ K / at most
add r − l + 1 per r
count exactly K
atMost(K) − atMost(K − 1)
count at least
valid at [l, r] ⇒ add n − r,or total − atMost(K − 1)
Check yourself 2 questions
  1. How do you count windows with exactly K distinct?

    Show answer

    atMost(K) − atMost(K−1).

  2. 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 stack/queue tool? 23-stack-and-queues#

Problem shape?
1Nearest element to the left/right that is bigger/smaller?
yes
monotonic stack:NGE: decreasing · NSE: increasing
no
2Every subarray's min/max summed or counted?
yes
contribution: a[i]·(i − PSE)·(NSE − i)strict on one side, ≤ on the other
no
3Max/min of a sliding window?
yes
monotonic deque of indices
no
4Rectangle / area under bars?
yes
histogram: compute area on pop(matrix → histogram per row)
no
5Matching / nesting / undo?
yes
plain stack: brackets, expression eval,asteroid collision
no
6O(1) cache by recency/frequency?
LRU
hashmap + doubly linked list
LFU
freq → LRU list + minFreq
Check yourself 2 questions
  1. Next greater element: stack order?

    Show answer

    Decreasing.

  2. 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 dec
Check yourself 2 questions
  1. Finding the middle without the length?

    Show answer

    Fast and slow pointers.

  2. 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#

Tree problem
1Answer depends on both subtrees' results?
yes
post-order: return info upward(height, diameter, max path, balanced)
no
2Per-level / per-column answer?
level
BFS by level size(zigzag, right view, width)
column
BFS with (node, col[, row])(vertical, top, bottom view)
no
3Need to move upward / radiate from a target node?
yes
parent map + BFS(distance K, burn tree)
no
4Two nodes' meeting point?
yes
LCA: return non-null side
no
5Rebuild / encode the tree?
yes
inorder + pre/post with index map;serialise with null markers
no
6O(1) extra space?
yes
Morris threads
no
plain DFS with path state(root-to-leaf, path sums)
Check yourself 2 questions
  1. Diameter, height or max path sum: which traversal?

    Show answer

    Post-order, returning info upward.

  2. 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 dec
Check yourself 2 questions
  1. Floor in a BST?

    Show answer

    Walk down keeping the best candidate.

  2. 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 dec
Check yourself 2 questions
  1. K largest elements: which heap and size?

    Show answer

    A min-heap of size k; the root is the kth largest.

  2. 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 dec
Check yourself 2 questions
  1. How do you check whether greedy is safe?

    Show answer

    Look for a counterexample that breaks the local choice.

  2. 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 dec
Check yourself 2 questions
  1. What does n & (n − 1) do?

    Show answer

    Clears the lowest set bit.

  2. 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#

String problem
1Balanced brackets, one bracket type?
yes
Depth counter — no stack neededoutermost: depth 0↔1 · nesting: max depth
no
2Parse text into a number?
symbols with values
Roman: subtract if smallerthan the next symbol
digits + sign + junk
atoi state machine:space → sign → digits → stopclamp before overflow
no
3Over all substrings?
palindrome
Expand around 2n − 1 centresO(n²) · Manacher O(n)
exactly k distinct
atMost(k) − atMost(k − 1)sliding window O(n)
per-substring frequency stat
Fix start, extend end,update int[26] incrementally
Check yourself 2 questions
  1. Balanced brackets of one type: need a stack?

    Show answer

    No, a depth counter is enough.

  2. 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 dec
Check yourself 2 questions
  1. Find one pattern in text with exact output?

    Show answer

    KMP, or Z on pattern#text.

  2. 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 dec
Check yourself 2 questions
  1. Max XOR of a pair?

    Show answer

    A binary trie, greedily taking the opposite bit.

  2. 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 dec
Check yourself 2 questions
  1. Nearly sorted small input?

    Show answer

    Insertion sort: O(n) best case.

  2. 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#

String problem
1Compare the string with its mirror?
yes
Two pointers l/rreverse · palindrome
no
2Only the character multiset matters?
yes
Count array int[26] / int[256]anagram · sort by frequency
no
3Structure-preserving char mapping?
yes
Two-way map / last-seen indexisomorphic
no
4Rotation?
yes
goal in s + srotate string
no
Directed scanLCP vertical · largest odd from the right
Check yourself 2 questions
  1. Anagram check?

    Show answer

    A count array (int[26]).

  2. 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 dec
Check yourself 2 questions
  1. Reverse a number's digits?

    Show answer

    Digit loop: d = n % 10; n //= 10.

  2. 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#

Prime question
1How many numbers?
one x
trial division to √x
[L, R], R ≤ 10¹², R − L ≤ 10⁶
segmented sieve
all x ≤ n, n ≤ 10⁷
2sieve of Eratosthenes
otherwise
3Need factors?
yes
SPF table, divide by spf[x]
range counts
prefix count pre[R] − pre[L−1]
Check yourself 2 questions
  1. Primes in [L, R] with R up to 10^12?

    Show answer

    A segmented sieve.

  2. 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)#

RecogniseComplexity
sorted array; pair/triplet sum; in-place rearrange; mergeO(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 -= 1
Pitfalls
  • 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
  1. Complexity of two pointers after sorting?

    Show answer

    O(n) plus the O(n log n) sort, O(1) space.

  2. 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)#

RecogniseComplexity
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
  1. Why is a variable window O(n)?

    Show answer

    Each index enters and leaves the window once.

  2. 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#

RecogniseComplexity
“how many subarrays with sum k”, negatives allowed, XOR k, longest sum kO(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) + 1
Pitfalls
  • 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
  1. Why initialise seen with {0: 1}?

    Show answer

    To count subarrays starting at index 0 (the empty prefix).

  2. 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#

RecogniseComplexity
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 iterations
Pitfalls
  • 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
  1. When feasible(mid) is true, what moves?

    Show answer

    hi = mid.

  2. 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#

RecogniseComplexity
next/prev greater/smaller; span; histogram; sum of subarray mins; window maxO(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
  1. What does the stack store?

    Show answer

    Indices, so you can compute distances and spans.

  2. 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#

RecogniseComplexity
K-th / top-K; merge k sorted; running median; always process cheapestO(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 largest
Pitfalls
  • 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
  1. Top-k complexity with a size-k heap?

    Show answer

    O(n log k).

  2. 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#

RecogniseComplexity
head may change; middle; Nth from end; cycle; palindromeO(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 start
Pitfalls
  • 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
  1. Detect a cycle?

    Show answer

    Floyd's fast and slow pointers meet if there's a cycle.

  2. 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#

RecogniseComplexity
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 up
Pitfalls
  • 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
  1. Diameter: what does dfs return and what goes to the global?

    Show answer

    Returns height (one arm); the global takes left + right.

  2. 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#

RecogniseComplexity
search, floor/ceil, kth, validate, iteratorO(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 left
Pitfalls
  • 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
  1. How do you validate a BST?

    Show answer

    Inorder must be strictly increasing (or pass min/max bounds).

  2. 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)#

RecogniseComplexity
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 marker
Pitfalls
  • 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
  1. How is a word's end marked in the dict trie?

    Show answer

    A special key such as '$'.

  2. 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#

RecogniseComplexity
intervals/meetings; jobs with deadlines; reach/jumps; counterexample doesn't break the local choiceO(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 = e
Pitfalls
  • 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
  1. Sort key for maximum non-overlapping intervals?

    Show answer

    The end time.

  2. 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#

RecogniseComplexity
pairs cancel; power of 2; subsets n ≤ 20; appears k timesO(1) / O(2ⁿ·n)
n & (n - 1)      # clear lowest set bit
x & -x           # lowest set bit
for mask in range(1 << n): ...   # all subsets
Pitfalls
  • 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
  1. Isolate the lowest set bit?

    Show answer

    x & −x.

  2. 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
  1. What does lower_bound return?

    Show answer

    The first index with a[i] ≥ x.

  2. 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
  1. Sum too small: which pointer moves?

    Show answer

    The left pointer moves right.

  2. 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
  1. When do you shrink the window?

    Show answer

    While the window is invalid (more than k distinct).

  2. 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
  1. Does prefix sum + hash map handle negatives?

    Show answer

    Yes.

  2. 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
  1. What's the default answer if no greater element exists?

    Show answer

    −1.

  2. 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
  1. Why a min-heap for the K largest?

    Show answer

    Its root is the smallest of the K kept, easy to evict.

  2. 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
  1. Why BFS for unweighted shortest paths?

    Show answer

    It explores in order of distance.

  2. 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
  1. How does Kahn's algorithm detect a cycle?

    Show answer

    Fewer than n nodes are output.

  2. 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
  1. Dijkstra's weight requirement?

    Show answer

    Non-negative edge weights.

  2. 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
  1. Name two uses of DSU.

    Show answer

    Any two of: connected components, undirected cycle detection, Kruskal's MST, grouping accounts.

  2. 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
  1. Grid word search with many words: why a trie?

    Show answer

    It prunes paths that aren't a prefix of any word.

  2. 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
  1. Three steps of backtracking?

    Show answer

    Choose, recurse, undo.

  2. 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
  1. Why loop capacity backwards in 0/1 knapsack?

    Show answer

    So each item is used at most once.

  2. 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
  1. LCS transition when characters match?

    Show answer

    dp[i][j] = dp[i−1][j−1] + 1.

  2. 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
  1. Variables needed to reverse a list?

    Show answer

    prev, the current node, and next.

  2. 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
  1. Max path sum: what's returned upward?

    Show answer

    node value + max(0, left, right): one arm.

  2. 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
  1. 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.

  2. 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#

PatternKey insight
Dutch national flag3 pointers low/mid/hi; swap mid↔hi without mid++
Boyer-Moore majoritycand/count; n/3 → 2 candidates + verify pass
Kadanecur=max(x,cur+x); reset when cur<0
Next permutationfind dip from right, swap with next larger, reverse suffix
Count inversions / reverse pairsmerge-sort counting during merge
Longest subarray sum kprefix map seed {0:-1}, store first index only
Count subarrays sum kseed {0:1}, add cnt[pre-k]
Subarrays XOR ksame as sum with XOR, seed {0:1}
Longest consecutiveset; only start from x where x-1 ∉ set
Check yourself 2 questions
  1. Dutch national flag pointers?

    Show answer

    low, mid and high; swap mid with high without advancing mid.

  2. 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#

ShapeTemplate
lower_boundfirst idx a[i] ≥ x
upper_boundfirst idx a[i] > x
rotated sortedone 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 bouquetssearch speed/day; ceil division
Gas stationssearch on real; iterate 100× or by count
Median of 2 sortedpartition smaller array; L1≤R2 & L2≤R1
Kth missinga[i]-(i+1) missing before i
Check yourself 2 questions
  1. upper_bound returns?

    Show answer

    The first index with a[i] > x.

  2. 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#

ShapeRule
Fixed size kadd right, drop left at i-k
Longest valid (variable)expand r; while invalid shrink l
Exactly K distinctatMost(K) − atMost(K−1)
Char replacementvalid while len − maxFreq ≤ k (maxFreq never decreases)
Min window substringneed-count + formed; shrink while formed
Count subarrays w/ conditionadd r-l+1 each step
Negatives presentwindow breaks → prefix sums / deque
Check yourself 2 questions
  1. Character replacement validity rule?

    Show answer

    Window length − max frequency ≤ k.

  2. 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#

ProblemStack keeps
Next greater elementdecreasing; pop smaller, answer = top
Previous smallerincreasing
Largest rectangle histogramincreasing; on pop area = h×(i−left−1)
Maximal rectanglehistogram per row
Sum of subarray minimumsPSE & NSE; contrib = a[i]·left·right (strict on one side)
Stock spandecreasing with counts
Asteroid collisionstack of right-movers
Remove K digitsincreasing; pop while top>d and k
Sliding window maxdeque of indices, decreasing
Check yourself 2 questions
  1. Largest rectangle in a histogram: area on pop?

    Show answer

    h × (i − left − 1).

  2. 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
  1. How do you find a cycle's start?

    Show answer

    After fast and slow meet, reset one to head and step both by one.

  2. 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#

ProblemInsight
Kth largestmin-heap size k
Merge K sortedheap of (val, list, idx)
Median of streammax-heap low + min-heap high; balance sizes
Task schedulermax(n_tasks, (f−1)(n+1)+#maxf)
Top K frequentcounter + heap or bucket sort O(n)
Meeting rooms IIsort starts, min-heap of end times
Jump gametrack farthest reach
Gas stationif total≥0 answer = start after last negative
Activity selection / non-overlapsort by end time
Candytwo passes left→right, right→left
Check yourself 2 questions
  1. Task scheduler formula?

    Show answer

    max(n_tasks, (f − 1)(n + 1) + count of max-frequency tasks).

  2. 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#

TaskTechniqueComplexityWatch out
Spiral orderKeep four boundaries (top, bottom, left, right); walk one edge, then shrink that boundaryO(mn)Check top ≤ bottom and left ≤ right again before the third and fourth edges
Rotate 90° clockwise in placeTranspose, then reverse each row (anticlockwise: transpose, then reverse each column)O(n²), O(1)Only square matrices rotate in place
Set matrix zeroesUse the first row and column as marker arrays, with two flags for themselvesO(mn), O(1)Process the first row and column last
Search a sorted matrixFully sorted: treat as 1D (i / n, i % n). Rows and columns sorted: staircase from the top-rightO(log mn) / O(m + n)Pick the right variant by reading how it's sorted
DiagonalsCells on one diagonal share i − j; anti-diagonals share i + jO(mn)Use i − j + (n − 1) as a non-negative key
Submatrix sums2D prefix sums (template below)O(mn) build, O(1) queryPad with a zero row and column to avoid bounds checks
Islands, flood fill, regionsBFS or DFS over 4 (or 8) neighbours; mark visited on entryO(mn)Deep recursion on 10⁶ cells: prefer an explicit stack or BFS
Shortest path in a gridBFS (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 pathGrid DP from top-left; one rolling row is enoughO(mn), O(n)Obstacles set dp to 0; initialise the first row and column carefully
Largest rectangle of 1sBuild a histogram per row, then largest rectangle with a monotonic stackO(mn)Reset heights to 0 on a 0 cell
Check yourself 2 questions
  1. Rotate a matrix 90° clockwise in place?

    Show answer

    Transpose, then reverse each row.

  2. 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#

ProblemInsight
Diameterheight fn returns 1 arm; global = l+r
Max path sumreturn 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 BSTpass (lo,hi) bounds
Kth smallest BSTinorder iterative, count
Views (top/bottom/left/right)BFS with column / level map
Serializepreorder with null markers
Build from pre+inmap inorder idx; recurse ranges
Burn tree / nodes at dist Kparent map + BFS
Morris traversalthread to predecessor, O(1) space
Balanced checkheight 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 nodesinorder walk; the two inversions name the swapped pair
Check yourself 2 questions
  1. 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.

  2. 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#

AlgoWhen / key rule
BFSunweighted shortest path; multi-source (rotten oranges)
DFScomponents, cycle (undirected: parent; directed: path-visited)
Topo (Kahn)indegree 0 queue; size≠n → cycle
DijkstraPQ of (d,node); skip stale entries; non-negative only
Bellman-Fordrelax V−1 times; Vth relax → negative cycle
Floyd-Warshallk outermost; dist[i][i]<0 → neg cycle
Prim / KruskalMST; Kruskal = sort edges + DSU
DSUpath compression + union by rank/size ≈ O(α)
Tarjan bridgesbridge if low[v] > tin[u]
Articulationlow[v] ≥ tin[u] (root: ≥2 children)
Kosaraju SCCorder by finish, reverse graph, DFS
0-1 BFSdeque: weight 0 → front, 1 → back
Check yourself 2 questions
  1. Undirected versus directed cycle detection with DFS?

    Show answer

    Undirected: track the parent; directed: track the current path.

  2. 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#

TopicKey
Triechildren[26] + end flag; count prefix
Max XOR pairbit trie, greedily take opposite bit
KMPLPS array; O(n+m)
Z-functionz[i] = longest prefix match starting at i; search on P$T
Rabin-Karprolling hash; verify on hit
Longest palindromeexpand around centre (2n−1 centres) / Manacher
XOR 1..n[n,1,n+1,0][n%4]
Lowest set bitx&-x; clear: x&(x-1)
Submask enumerations=(s-1)&mask
Sievemark from p², O(n log log n); SPF sieve for factorisation
Fast powerbinary exponentiation mod M
Check yourself 2 questions
  1. KMP complexity?

    Show answer

    O(n + m).

  2. 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#

TriggerTool
range sum + point updateFenwick (BIT)
range update + range querylazy segment tree
static range min, many queriessparse table O(1)
count numbers in [L,R] with digit propertydigit DP
answer for every rootrerooting DP
k-th ancestor / LCA many queriesbinary lifting
n≈40 subset sumsmeet-in-the-middle
random sample from streamreservoir sampling
Check yourself 2 questions
  1. Range sum with point updates?

    Show answer

    Fenwick tree (BIT).

  2. 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 dec
Check yourself 2 questions
  1. Edge weights 0 or 1?

    Show answer

    0-1 BFS with a deque.

  2. 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#

TechniqueHowUse for
Reservoir samplingKeep the first k; for item i (1-based) replace a random slot with probability k / iUniform sample from a stream of unknown length; random node of a linked list
Fisher–Yates shuffleFor 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 weightPrefix sums of weights, draw r in [1, total], binary search the first prefix ≥ rWeighted sampling, load balancing by capacity
Randomised quickselectRandom pivot, recurse into one sideKth element in expected O(n)
Rejection samplingGenerate a larger uniform range, discard values outside the target rangerand10 from rand7 (use 7·(a−1)+b, reject > 40)
Random hashingRandom base or modulus for rolling hashesMake adversarial collisions unlikely
Skip listEach node promoted to the next level with probability ½Ordered set with expected O(log n) ops (Redis sorted sets)
Check yourself 2 questions
  1. Reservoir sampling: when does item i replace a slot?

    Show answer

    With probability k / i.

  2. 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#

(a + b) mod m, (a · b) mod m → reduce after every operationa / b mod p = a · b^(p−2) mod p (p prime, Fermat inverse)nCr mod p = fact[n] · inv[r] · inv[n−r] (precompute factorials)Catalan(n) = C(2n, n) / (n + 1) (BST shapes, valid parentheses)Fibonacci in O(log n): [[1,1],[1,0]]^n (matrix exponentiation)cross(o, a, b) = (a−o)×(b−o) > 0 → counter-clockwise turnpolygon area = ½ |Σ (xᵢ·yᵢ₊₁ − xᵢ₊₁·yᵢ)| (shoelace)
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
  1. Modular inverse of b mod prime p?

    Show answer

    b^(p−2) mod p.

  2. 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 dec
Check yourself 2 questions
  1. Undirected cycle detection with edges arriving online?

    Show answer

    DSU: an edge joining two nodes already connected makes a cycle.

  2. 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#

GoalAlgorithmKey detail
Shortest path, unweightedBFSmark visited on enqueue not dequeue
Shortest path, weighted (≥0)Dijkstraif d > dist[u]: continue for stale entries
Shortest path, negative weightsBellman-Fordcopy dist each round, N−1 iterations
Connectivity / componentsDFS + outer loopcount how many times outer loop fires
Ordering with dependenciesTopo sort (Kahn)len(order) != n → cycle
Cycle in directed graph3-state DFS (0/1/2)state 1 = on current stack
Cycle in undirected graphDFS + parent / DSUnei != parent
BipartiteBFS, flip colourscontradiction = not bipartite
Closest source distanceMulti-source BFSseed all sources at distance 0
Can X reach Y cheaplyReverse BFS/DFS from YPacific Atlantic
All pairs, V ≤ ~400Floyd-Warshallk outermost
Connect everything cheaplyKruskal (DSU) / Prim (heap)
Critical edges / SCCTarjan low-link / Kosarajulow[v] > tin[u] ⇒ bridge
3 questions first: What am I looking for? Directed/weighted? Could it be disconnected (outer loop)?
Check yourself 2 questions
  1. When should BFS mark nodes visited?

    Show answer

    On enqueue, not dequeue.

  2. 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
  1. What goes wrong if you mark on dequeue?

    Show answer

    Duplicates in the queue and wrong distances.

  2. 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
  1. Why is the outer loop mandatory?

    Show answer

    Graphs can be disconnected; one DFS misses other components.

  2. 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
  1. What do the three states mean?

    Show answer

    0 new, 1 on the current path (stack), 2 done.

  2. 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
  1. What does len(order) < n mean?

    Show answer

    The graph has a cycle.

  2. 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
  1. Why skip when du > dist[u]?

    Show answer

    The entry is stale; a shorter path was already processed.

  2. 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
  1. Why copy the distance array each round?

    Show answer

    So one round can't chain several edges, which would break the stop limit.

  2. 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
  1. Which loop must be outermost?

    Show answer

    k, the intermediate node.

  2. 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
  1. What does Prim's heap hold?

    Show answer

    (weight, node) edges leaving the tree.

  2. 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
  1. Kruskal's order of edges?

    Show answer

    Ascending weight.

  2. 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.

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
  1. Kosaraju's two passes?

    Show answer

    DFS for finish order, then DFS on the reversed graph in reverse finish order.

  2. 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
  1. Where do 0-weight neighbours go?

    Show answer

    The front of the deque (appendleft).

  2. 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) == n check
  • Bellman-Ford updating dist in place — copy before each round
  • DSU: parent = [0]*n; forgetting return False when 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
  1. Parent-tracking DFS on a directed graph: problem?

    Show answer

    It misses directed cycles; use 3-state colouring.

  2. 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#

ProblemLCPattern
Number of Islands200Grid DFS
Clone Graph133DFS + hashmap
Pacific Atlantic417Reverse DFS from borders
Course Schedule I/II207/210Topo sort (Kahn)
Word Ladder127BFS + string transform
Rotting Oranges994Multi-source BFS
Network Delay Time743Dijkstra
Cheapest Flights K Stops787Bellman-Ford
Redundant Connection684DSU / cycle
Is Graph Bipartite785BFS 2-colouring
Alien Dictionary269Topo sort on characters
Accounts Merge721DSU + sorting
Check yourself 2 questions
  1. Course Schedule I/II pattern?

    Show answer

    Topological sort (Kahn).

  2. 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]…
Always: recursive → top-down (add memo) → bottom-up (flip direction) → space-optimise
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 dec
Check yourself 2 questions
  1. First DP question?

    Show answer

    What does dp[i] mean, as an exact sentence?

  2. 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#

SignalPattern
1D array, choices affect neighbours1D linear
grid, move right/down2D grid
two strings, alignment / edittwo-sequence
take or leave with capacityknapsack (0/1 backward, unbounded forward)
longest increasing / chainLIS family
burst / cut / merge contiguousinterval (fill by length)
node needs children firsttree DP (postorder, return pair)
buy/sell with rulesstock state machine
n ≤ 20, subset statebitmask DP
count integers ≤ N with propertydigit DP (L4+)
Knapsack direction rule (most common mistake):
  • 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
  1. Two strings with alignment or edits?

    Show answer

    Two-sequence DP.

  2. 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#

FamilyStateTransitionBaseFill orderAnswer / optimise
1D lineardp[i] = best/ways up to iClimb: 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 griddp[i][j] = paths/cost to (i,j)dp[i][j] = g + min(up, left); paths = up + leftrow 0 / col 0; blocked = 0row by rowdp[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 variantscash 0, hold −∞day ↑sell state
0/1 knapsack / subsetdp[i][t] = can/ways/max with items ..i, capacity tnot-take dp[i−1][t]; take dp[i−1][t−w]dp[0] = True / 1t DESCENDING (1D)dp[target]
Unbounded knapsackdp[t] with reusable itemstake → stay at i: dp[t−w] same rowdp[0] = 0 (min) / 1 (ways)t ASCENDINGdp[amount]
LIS familydp[i] = longest ending at idp[i] = 1 + max dp[j], j‹i, a[j]‹a[i]; or tails + lower_bounddp[i] = 1i ↑, j ‹ imax(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 stringi ↑, 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] + costdp[i][i] = 0by LENGTH (i ↓, j ↑)dp[0][n−1]; burst balloons: choose LAST
Tree DPf(node) returns pair/statesrob = val + skipL + skipR; skip = max(L)+max(R)null → (0,0)postordermax(f(root))
Bitmask DPdp[mask][last]dp[mask|1‹‹v][v] = min(dp[mask][u] + w)dp[1‹‹s][s] = 0masks ↑min over last of dp[full][last]
Check yourself 2 questions
  1. Climbing stairs transition?

    Show answer

    dp[i] = dp[i−1] + dp[i−2].

  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
  1. Space-optimised climbing stairs?

    Show answer

    Keep only prev1 and prev2: O(1) space.

  2. 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
  1. Unique paths with a rolling row?

    Show answer

    row[j] += row[j−1].

  2. 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
  1. Single transaction best profit?

    Show answer

    price − running minimum, maximised.

  2. 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
  1. Subset sum transition?

    Show answer

    dp[t] |= dp[t − x], t descending.

  2. 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
  1. Minimum coins transition?

    Show answer

    dp[t] = min(dp[t], 1 + dp[t − c]), t ascending.

  2. 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
  1. LIS O(n log n) method?

    Show answer

    A tails array with lower_bound replace or append.

  2. 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
  1. Longest common substring: mismatch transition?

    Show answer

    Reset to 0.

  2. 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
  1. MCM fill order?

    Show answer

    i from n−1 down, j from i+1 up (by interval length).

  2. 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
  1. Binary Tree Cameras states?

    Show answer

    0 needs a camera, 1 has one, 2 covered.

  2. 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
  1. Two branches at each knapsack node?

    Show answer

    Exclude the item, or include it (if it fits).

  2. 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
  1. Why is naive Fibonacci exponential?

    Show answer

    It recomputes the same subproblems repeatedly.

  2. 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: wait
Check yourself 2 questions
  1. What does the cooldown transition do?

    Show answer

    Sold must wait a day before returning to rest.

  2. 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
  1. Knapsack loop direction rule?

    Show answer

    Backward for 0/1, forward for unbounded.

  2. 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#

DP patterns9 areas · 28 topics · select a topic to jump to it
010/1 Knapsack4
Subset sumEqual partitionCount subsets diffTarget sum
02Unbounded4
Coin change ways/minRod cuttingPerfect squaresWord break
03LCS family4
LC substringEdit distanceLPS / SCSDistinct subsequences
04LIS family3
Russian dollBitonicLargest divisible subset
05Kadane3
CircularMax productStocks I II III
06MCM / interval3
Burst balloonsPalindrome partitionBoolean parenthesization
07Grid3
Unique pathsDungeon reverseCherry pickup
08Trees and graphs2
House robber IIIDAG longest path
09Bitmask2
TSPPartition K equal

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)
FamilyState · transition
0/1 knapsackdp[i][w]=max(dp[i-1][w], v+dp[i-1][w-wt]); 1D: iterate w descending
Unboundedsame but dp[i][w-wt]; 1D iterate w ascending
Coin waysloop coins outer → combinations; amount outer → permutations
LCSmatch → 1+diag; else max(up,left)
Edit distancematch → diag; else 1+min(ins,del,rep)
LPSLCS(s, reverse(s)); min deletions = n−LPS
SCSm+n−LCS
LISO(n log n): tails + bisect_left; print → parent array
Russian dollsort w asc, h desc, LIS on h
Kadane circularmax(maxK, total−minK) unless all negative
Max producttrack max & min (negatives flip)
Stocks w/ kbuy[k], sell[k] state machine; cooldown/fee variants
MCM / intervaldp[i][j]=min over k; fill by length
Burst balloonsk = last balloon burst in (i,j)
Dungeonfill from bottom-right: need = max(1, min(next)−cell)
Cherry pickuptwo walkers at once: (r1,c1,r2), c2=r1+c1−r2
Tree DPreturn (rob, notRob) pair
Bitmask TSPdp[mask][last], O(2^n·n²)
Partition K equalbitmask + bucket fill, or backtrack with sort desc
Check yourself 2 questions
  1. What defines the state?

    Show answer

    What changes between calls: index, capacity, last pick, mask.

  2. Order of optimisation?

    Show answer

    Memoise, tabulate, then optimise space.

Takeaway State, choices, base cases, then memo → tabulate → space-optimise.

Advanced DP templates#

FamilyStateTransitionClassic 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 DPdp[mask][last] over subsets, n ≤ ~20Add one unvisited element to the maskTravelling salesman, assign tasks to workers, shortest superstring
Rerootingdown[v] from children, then up[v] from the parent's sideTwo DFS passes; answer at v combines bothSum of distances in tree, best root for some metric
DP on DAGsValue per node in topological orderRelax all outgoing edgesLongest path, count paths, course schedule with durations
Probability / expectationExpected value from a stateWeighted sum of next states' expectationsKnight probability, dice games, soup servings
Reconstructing the answerStore the choice made at each stateWalk choices back from the final statePrint 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
  1. Digit DP state?

    Show answer

    (position, tight, started, extra such as sum or mask).

  2. 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/)
PatternProblems
0/1 Knapsacksubset sum, equal subset partition, count subsets with sum, min subset sum diff, target sum, count subsets with given diff
Unboundedcoin change (ways, min coins), rod cutting, min cost tickets, perfect squares, word break, integer break
LCSlongest common substring, edit distance, LPS, SCS, distinct subsequences, min insert/delete to convert, wildcard / regex matching
LISmax sum increasing subseq, Russian doll, bitonic, box stacking, building bridges, largest divisible subset, number of LIS
Kadanemax subarray, circular, max product, stocks I/II/III/IV, cooldown, fee
MCMmatrix chain, burst balloons, palindrome partitioning II, boolean parenthesization, optimal BST, min cost to cut stick
Gridunique paths I/II, min path sum, triangle, dungeon game, gold mine, cherry pickup, max falling path
Treeshouse robber III, max path sum, diameter, binary tree cameras
GraphsDAG longest path, course schedule, cheapest flights within K stops (Bellman-Ford K rounds), Hamiltonian path
BitmaskTSP, 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 dec
Check yourself 2 questions
  1. Pick/not-pick leaf count?

    Show answer

    2ⁿ.

  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
DFS: 3 questions
  • 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)
4 rules that never change: base case first · mark visited before recursing · snapshot path[:] · every append has a pop
def 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
  1. Four parts of a recursive solution?

    Show answer

    Base case, recursive step, combine results, trust the recursion.

  2. 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
  1. Leaves for [1, 2]?

    Show answer

    [1,2], [1], [2], [].

  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
  1. Why start from index start?

    Show answer

    To avoid revisiting earlier elements and duplicating combinations.

  2. 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
  1. When is a board recorded?

    Show answer

    When row == n.

  2. 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
  1. Name two easy recursion problems.

    Show answer

    Any two of: factorial, Fibonacci, sum of digits, power, reverse string, palindrome, recursive binary search.

  2. 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
  1. Name two medium recursion problems.

    Show answer

    Any two of: subsets, permutations, Tower of Hanoi, combination sum, phone letters, generate parentheses.

  2. 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
  1. Name two hard recursion problems.

    Show answer

    Any two of: N-Queens, Sudoku, Word Search II, palindrome partitioning, wildcard or regex matching.

  2. 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
  1. How do you skip duplicates?

    Show answer

    Sort, then skip when i > start and a[i] == a[i−1].

  2. 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
  1. Sliding window with negatives: what instead?

    Show answer

    Prefix sums.

  2. 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#

StartLikely follow-up
Two Sumsorted → 2 ptr; 3Sum/4Sum; BST input; stream (design)
Sliding windowat most K → exactly K; with negatives
Binary searchrotated; duplicates; 2D matrix; on answer
Tree DFSiterative; return path; O(1) space (Morris)
Linear DPspace-optimise; print solution; k transactions
Backtrackingduplicates; count only (→ DP); prune
Graph BFSweighted → Dijkstra; multi-source; bidirectional
Intervalsinsert; min rooms; free time
Heapstream; k sorted lists; lazy deletion
Check yourself 2 questions
  1. Likely follow-up to Two Sum?

    Show answer

    Sorted input with two pointers, then 3Sum/4Sum, BST input, or a streaming design.

  2. 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#

StructureAccessSearchInsertDeletePythonJava
Array / listO(1)O(n)O(1) end, O(n) midO(n)listint[] / ArrayList
Hash map / set—O(1) avgO(1) avgO(1) avgdict / set / CounterHashMap / HashSet
Stacktop O(1)O(n)push O(1)pop O(1)list append/popArrayDeque push/pop
Queue / dequeends O(1)O(n)O(1)O(1)collections.dequeArrayDeque offer/poll
Heapmin O(1)O(n)O(log n)pop O(log n)heapq (min only)PriorityQueue
Linked listO(n)O(n)O(1) at nodeO(1) at nodecustom Nodecustom / LinkedList
BST (balanced)O(log n)O(log n)O(log n)O(log n)sortedcontainers / bisectTreeMap / TreeSet
Trie—O(L)O(L)O(L)nested dictNode[26]
DSU—find ≈O(1)union ≈O(1)—parent listint[] parent
Segment tree—query O(log n)update O(log n)—array 4nint[4n]
Fenwick (BIT)—prefix O(log n)add O(log n)—tree[n+1], i += i & −isame
Check yourself 2 questions
  1. Hash map average lookup?

    Show answer

    O(1).

  2. 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
  1. Update step in a Fenwick tree?

    Show answer

    i += i & −i.

  2. 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#

ProblemCore structureThe trickCost
Min stackStack of (value, min so far)Each entry remembers the minimum at the time it was pushedO(1) all ops
Queue using stacksIn-stack + out-stackPour in → out only when out is emptyAmortised O(1)
LRU cacheHash map + doubly linked listMove to front on access; evict from the tailO(1)
LFU cacheKey map + frequency → linked list + minFreqOn access, move the key to the next frequency list; evict from minFreq's tailO(1)
Insert, delete, getRandom O(1)Array + value → index mapDelete by swapping with the last element, then popO(1)
Hit counter (last 5 minutes)Circular buffer of 300 (time, count) or a dequeOverwrite a slot when its timestamp is staleO(1) / O(window)
Time-based key-value storeMap key → list of (timestamp, value)Timestamps arrive increasing, so binary search for the last ≤ tO(log n) get
Snapshot arrayPer index: list of (snap_id, value)Only record changes; binary search by snap_idO(log s) get
Median of a streamMax-heap low half + min-heap high halfRebalance so sizes differ by at most oneO(log n) add, O(1) median
Iterators (peeking, BST, flatten nested list)Cached next element / stack of the left spine / stack of iteratorsPrepare the next item lazily in hasNext()Amortised O(1)
Design Twitter feedPer-user tweet lists + heap mergeMerge the latest tweets of followees with a heap of size kO(f log f) per feed
Range sum with updatesFenwick tree or segment treePoint update + prefix queryO(log n)
Circular queue / dequeFixed array + head index + sizeIndex with (head + i) % capacityO(1)
Hash map from scratchArray of buckets with chainingHash then mod capacity; resize ×2 at load factor ~0.75O(1) average
AutocompleteTrie storing the top-k suggestions per nodeUpdate top-k lists on insert; a query is one walkO(prefix length)
Check yourself 2 questions
  1. Min stack trick?

    Show answer

    Each entry stores the minimum at push time.

  2. 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#

NeedPythonJava
map countcnt[k] = cnt.get(k, 0) + 1map.merge(k, 1, Integer::sum)
get defaultd.get(k, 0)map.getOrDefault(k, 0)
lista = []; 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)
stackst.append(x); st.pop(); st[-1]Deque<Integer> st = new ArrayDeque<>(); push/pop/peek
queueq = deque(); q.append; q.popleft()Queue<Integer> q = new LinkedList<>(); offer/poll/peek
min-heapheapq.heappush(h, x)new PriorityQueue<>()
max-heappush -xnew PriorityQueue<>(Comparator.reverseOrder())
sort by keya.sort(key=lambda p: (p.city, p.name))list.sort(Comparator.comparing(Person::city).thenComparing(Person::name))
sort arraya.sort() (returns None!)Arrays.sort(a)
string build''.join(parts)StringBuilder sb; sb.append(x); sb.toString()
char ats[i]s.charAt(i)
substrings[1:4]s.substring(1, 4)
equality==s.equals(t) (== compares references)
int division5 // 25 / 2 == 2; (double) 5 / 2
iterate mapfor k, v in d.items()for (Map.Entry<K,V> e : map.entrySet())
Check yourself 2 questions
  1. Java equivalent of cnt[k] = cnt.get(k, 0) + 1?

    Show answer

    map.merge(k, 1, Integer::sum).

  2. 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 a List<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 - b overflows; use Integer.compare(a, b)
  • Java: Math.abs(Integer.MIN_VALUE) is still negative; widen to long
  • Java: 'a' + 1 is an int; cast back with (char) ('a' + 1)
  • Python: [[0] * n] * m shares one row m times; use [[0] * n for _ in range(m)]
  • Python: heapq is 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
  1. Why is Integer 128 == 128 false in Java?

    Show answer

    Only −128 to 127 are cached; == compares references.

  2. 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.

434 problems
TopicProblemBest approach — ideaTimeSpaceCommon mistakeInterview angle
Basic mathsCount All Digits of a NumberOptimal — logarithm — ⌊log₁₀ n⌋ + 1O(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 mathsCount Number of Odd Digits in a NumberOptimal — digit loop — d = n % 10; test parityO(log₁₀ n)O(1)Checking n % 2 (the parity of the whole number) instead of d % 2.
Basic mathsReverse a NumberOptimal — arithmetic build — rev = rev*10 + dO(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 mathsPalindrome NumberOptimal — reverse half — stop when rev ≥ nO(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 mathsReturn the Largest Digit in a NumberOptimal — digit loop — best = max(best, n % 10)O(log₁₀ n)O(1)Initialising best = -1 and then returning -1 for n = 0.
Basic mathsFactorial of a Given NumberOptimal — iterative product — res *= i for i in 2..nO(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 mathsCheck if the Number is ArmstrongOptimal — 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 mathsCheck for Perfect NumberOptimal — √n pairs — sum i and n/i for i ≤ √nO(√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 mathsCheck for Prime NumberOptimal — 6k ± 1 — after 2 and 3, test only 6k±1O(√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 mathsCount of Prime Numbers till NOptimal — 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 mathsGCD of Two NumbersOptimal — modulo Euclid — a, b = b, a % bO(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 mathsLCM of Two NumbersOptimal — via GCD — a / gcd * bO(log min(a,b))O(1)Computing a * b / g, where a * b overflows even when the LCM fits.
Basic mathsDivisors of a NumberOptimal — two lists — small asc + large desc reversedO(√n)O(d)Adding √n twice for perfect squares.
Basic arraysSum of Array ElementsOptimal — accumulator — s += xO(n)O(1)accumulate(..., 0) in C++. The int init makes the whole sum int.
Basic arraysCount of Odd Numbers in ArrayOptimal — bit test — cnt += x & 1O(n)O(1)x % 2 == 1 in C++/Java, which misses negative odds.
Basic arraysCheck if the Array is SortedOptimal — adjacent pairs — first a[i-1] > a[i] → falseO(n)O(1)Using >= in the check, which rejects ties.
Basic arraysReverse an ArrayOptimal — two pointers — swap ends, move inwardO(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 hashingHighest Occurring Element in an ArrayOptimal — frequency map — count, then scan entriesO(n)O(k) distinctRelying 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 hashingSecond Highest Occurring ElementOptimal — 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 hashingSum of Highest and Lowest FrequencyOptimal — map, then min/max — one count pass + one scanO(n)O(k)Initialising lo = 0, so the min never updates.
Basic stringsReverse a StringOptimal — two pointers — swap ends, move inwardO(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 stringsPalindrome CheckOptimal — two pointers — compare ends, move inwardO(n)O(1)Comparing s[i] with s[n − i], which is off by one.
Basic stringsLargest Odd Number in a StringOptimal — rightmost odd + strip zeros — end at the rightmost odd digit, start at the first non-zeroO(n)O(1) extraint(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 stringsLongest Common PrefixOptimal — vertical scan — compare column i across all stringsO(S) total charsO(1) extraIndexing s[i] before checking i < len(s).
Basic stringsIsomorphic StringsOptimal — last-seen index arrays — last_s[s[i]] == last_t[t[i]] at every iO(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 stringsRotate StringOptimal — substring of s + s — goal in s + sO(n) with KMP; O(n²) worst case naiveO(n)Dropping the length check.
Basic stringsValid AnagramOptimal — count array — +1 for s, −1 for t, all zeroO(n)O(26)Comparing character *sets*, which ignores multiplicity.
Basic stringsSort Characters by FrequencyOptimal — bucket by frequency — bucket[f] ← chars; walk f = n..1O(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 recursionSum of First N NumbersFunctional recursion — return N + f(N − 1)O(N)O(N) stackBase 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 recursionFactorial of a Given NumberFunctional recursion — return n · f(n − 1)O(n)O(n) stackBase case returning 0, which makes every product 0.
Basic recursionSum of Array ElementsOptimal — recursion on an index — f(i) = nums[i] + f(i + 1)O(n)O(n) stackSlicing per call (O(n²)).
Basic recursionReverse a String (Recursive)Optimal — swap ends, recurse inward — swap(l, r); f(l + 1, r − 1)O(n)O(n) stack + O(n) bufferBase case l == r only: for even n the pointers cross and never become equal → infinite recursion / out of bounds.
Basic recursionCheck if String is Palindrome or NotOptimal — recurse on (l, r) — s[l]==s[r] and f(l+1, r−1)O(n)O(n) stackr = len(s) − 1 as a Python default argument: it would be evaluated once at definition time, so use None.
Basic recursionCheck if a Number is Prime or NotOptimal — recurse over 2..√n — stop when i·i > numO(√n)O(√n) stackTreating 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 recursionReverse an Array (Recursive)Single index i — swap(i, n−1−i); f(i + 1)O(n)O(n) stackStopping at i >= n instead of n/2: it swaps everything twice and leaves the array unchanged.
Basic recursionCheck if the Array is SortedOptimal — 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 recursionSum of Digits in a Given NumberOptimal — % 10 recursion — n % 10 + f(n // 10)O(d) = O(log n)O(log n) stackPython / instead of //: float division never reaches 0 cleanly.
Basic recursionFibonacci NumberOptimal — 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
SortingSelection SortSelection sort — swap min of [i, n) into iO(n²) in every caseO(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
SortingBubble SortOptimised — early exit with swapped — stop after a pass with no swapsO(n²) worst / avg, O(n) bestO(1)Inner loop to n − 1 every pass, re-checking the finished tail.
SortingInsertion SortShift-based (standard) — hold key, shift larger right, place onceO(n²) worst / avg, O(n) bestO(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.
SortingMerge SortTop-down recursive merge sort — sort(l, m), sort(m+1, r), merge(l, m, r)O(n log n) best / avg / worstO(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
SortingQuick SortTwo-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 jO(n log n) avg / best, O(n²) worst (rare with random pivot)O(log n) avg stackMissing 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
SortingRecursive Bubble SortRecursive outer loop — one pass, then f(n − 1)O(n²) worst, O(n) bestO(n) stackRecursing with n instead of n − 1 → infinite recursion.
SortingRecursive Insertion SortHead recursion on n (classic) — f(n − 1), then insert nums[n − 1]O(n²) worst, O(n) bestO(n) stackInserting before recursing in the head-recursive version: that inserts into an unsorted prefix.
ArraysLinear SearchLinear scan — return at the first matchO(n)O(1)Returning inside the loop's else branch (−1 after checking only index 0).
ArraysLargest ElementSingle pass — track the running maxO(n)O(1)best = 0 → wrong for all-negative input.
ArraysSecond Largest ElementOne pass, top-2 tracking — demote first → second on a new maxO(n)O(1)elif x > second without x < first → duplicates of the max become the second.
ArraysMaximum Consecutive OnesRunning streak — cnt++ on 1, cnt = 0 on 0O(n)O(1)Updating best only when a 0 is seen → misses a trailing run.
ArraysLeft Rotate Array by OneSave first, shift, place — temp = nums[0]; shift left; nums[n−1] = tempO(n)O(1)Not saving nums[0] before overwriting it.
ArraysLeft Rotate Array by K PlacesThree reversals — rev(0,k−1), rev(k,n−1), rev(0,n−1)O(n)O(1)Forgetting k %= n → out-of-range indices.
ArraysMove Zeros to EndTwo pointers (write index) — swap each non-zero into position jO(n)O(1)Swapping zeros with the *next* non-zero using nested loops → O(n²).
ArraysRemove Duplicates from Sorted ArrayTwo pointers — i = last unique, j scansO(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.
ArraysFind Missing NumberXOR — XOR of 0..n and all numsO(n)O(1)Using n = len + 1 when the range is 0..n (it's 1..n in some variants; read the statement).
ArraysUnion of Two Sorted ArraysTwo-pointer merge with dedupe — take the smaller head; skip if equal to the last outputO(n + m)O(1) beyond the outputForgetting to dedupe the leftover tail.
ArraysIntersection of Two Sorted ArraysTwo pointers — advance the smaller; equal → take and advance bothO(n + m)O(1) beyond the outputAdvancing only one pointer on a match → the same element counted repeatedly.
ArraysMajority Element IBoyer–Moore voting — cand/cnt; cancel unequal pairsO(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.
ArraysLeaders in an ArrayRight-to-left suffix max — leader iff nums[i] > maxRightO(n)O(1) beyond the output>= instead of > (duplicates become leaders).
ArraysRearrange Array Elements by SignSingle pass, two write indices — pos → even slot, neg → odd slotO(n)O(n) for the outputSwapping in place: breaks the relative order.
ArraysPrint the Matrix in Spiral MannerFour boundaries — right, down, left, up; shrink after each sideO(m · n)O(1) beyond the outputMissing 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.
ArraysPascal's Triangle IRunning product nCr — res = res·(n − i)/(i + 1), i < kO(min(k, n − k))O(1)Off-by-one: using C(r, c) instead of C(r − 1, c − 1).
ArraysPascal's Triangle IIIncremental product — val = val · (n − k) / (k + 1)O(r)O(1) beyond the outputUpdating the DP row left to right (it reads values that were already overwritten).
ArraysPascal's Triangle IIIAdditive DP — row[j] = prev[j − 1] + prev[j]O(n²)O(1) beyond the outputInner loop from j = 0, which reads prev[−1].
ArraysRotate Matrix by 90 DegreesTranspose + reverse rows — swap(m[i][j], m[j][i]) for j > i; reverse each rowO(n²)O(1)Transposing the full matrix (j from 0) → swaps everything twice, so nothing changes.
ArraysSet Matrix ZeroesFirst row/column as markers — mat[i][0], mat[0][j] are the flags; col0 for column 0O(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.
ArraysTwo SumOne-pass hash map — seen[value] = index; look up target − x firstO(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.
Arrays3 SumSort + two pointers — fix i; l = i + 1, r = n − 1; skip duplicatesO(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].
Arrays4 SumSort + two fixed + two pointers — i, j loops with skips; l/r on the restO(n³)O(1) beyond the output32-bit sum → false matches after overflow.
ArraysSort an Array of 0s, 1s and 2sDutch National Flag — low/mid/high; 0 → swap low, 1 → skip, 2 → swap highO(n), one passO(1)mid++ after swapping with high → the swapped-in 2 or 0 is never examined.
ArraysKadane's Algorithm: Maximum Subarray SumKadane — 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.
ArraysNext PermutationPivot, swap, reverse — find the dip from the right; swap with the next larger; reverse the suffixO(n)O(1)> instead of >= when finding the pivot → wrong with duplicates.
ArraysMajority Element IIExtended Boyer–Moore — two candidates; a third value decrements both; verifyO(n)O(1)Skipping verification.
ArraysFind the Repeating and Missing NumberSum and sum-of-squares equations — x − y and x² − y² → x + yO(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).
ArraysCount InversionsMerge sort with counting — cross inversions += mid − i + 1 when right winsO(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.
ArraysReverse PairsMerge 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).
ArraysMaximum Product SubarrayMax/min ending here — hi, lo = max/min(x, x·hi, x·lo)O(n)O(1)Tracking only the max (misses negative × negative).
ArraysMerge Two Sorted Arrays Without Extra SpaceThree 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
ArraysCheck if array is sorted and rotatedCount circular drops — drops where a[i] > a[(i+1)%n]; answer drops ≤ 1O(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
HashingLongest Consecutive Sequence in an ArrayHash set, start only at run starts — x is a start iff x − 1 ∉ set; walk up from startsO(n) averageO(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.
HashingLongest Subarray with Sum KPrefix sum + first-index map — first[p] = earliest index; seed {0: −1}; len = i − first[p − k]O(n) averageO(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.
HashingLargest Subarray with Sum 0Equal prefix sums — first[p]; on repeat, len = i − first[p]O(n) averageO(n)Missing {0: −1} → misses prefixes that are 0 themselves.
HashingCount Subarrays with Given SumPrefix sum + count map — ans += cnt[p − k]; then cnt[p] += 1; seed {0: 1}O(n) averageO(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.
HashingCount Subarrays with Given XOR KPrefix XOR + count map — ans += cnt[x ^ k]; then cnt[x] += 1; seed {0: 1}O(n) averageO(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 searchSearch X in Sorted ArrayIterative binary search — closed interval [lo, hi]; drop the half that can't hold targetO(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 searchLower BoundBinary search with an answer variable — nums[mid] ≥ x → ans = mid, go left; else go rightO(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 searchUpper BoundBinary search — nums[mid] > x → ans = mid, go left; else go rightO(log n)O(1)Confusing with lower bound (≥ vs >).
Binary searchSearch Insert PositionLower bound — answer-variable binary search with ≥O(log n)O(1)Returning −1 when not found.
Binary searchFloor and Ceil in Sorted ArrayTwo binary searches — floor: last nums[i] ≤ x · ceil: first nums[i] ≥ xO(log n)O(1)Returning indices when values were asked (or vice versa) — clarify.
Binary searchFirst and Last OccurrenceOne 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 searchSearch in Rotated Sorted Array IOne pass: pick the sorted half — nums[lo] ≤ nums[mid] → left sorted; test range, else go rightO(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 searchSearch in Rotated Sorted Array IIRotated search with tie shrinking — if lo, mid, hi all equal: lo++, hi−−; else as in part IO(log n) average, O(n) worstO(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 searchFind Minimum in Rotated Sorted ArrayCompare 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 searchFind Out How Many Times the Array Is RotatedIndex of minimum — nums[mid] > nums[hi] → lo = mid + 1, else hi = mid; return loO(log n)O(1)Returning the minimum's value instead of its index.
Binary searchSingle Element in a Sorted ArrayBinary search on even indices — force mid even; pair intact → lo = mid + 2, else hi = midO(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 searchCount Occurrences in a Sorted ArrayUpper bound − lower bound — two binary searchesO(log n)O(1)Finding one occurrence then counting outward — O(n).
Binary searchFind Square Root of a NumberBinary search on the answer — mid² ≤ n → ans = mid, lo = mid + 1; else hi = mid − 1O(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 searchFind Nth Root of a NumberBinary search with capped power — pow(mid, n) returns 0/1/2 for < / = / > mO(n log m)O(1)Library pow + cast — rounding errors.
Binary searchFind the Smallest DivisorBinary 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 searchKoko Eating BananasBinary search on speed — hours(k) ≤ h → ans = k, go left; else go rightO(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 searchMinimum Days to Make M BouquetsBinary search on day — impossible if m·k > n; else first d in [min, max] with bouquets(d) ≥ mO(n log(max − min))O(1)Not resetting run after forming a bouquet (flowers reused).
Binary searchCapacity to Ship Packages Within D DaysBinary search on capacity — days_needed(cap) ≤ days → go left; greedy checkO(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 searchKth Missing Positive NumberBinary search on missing count — missing(i) = arr[i] − i − 1; first i with missing ≥ k; return lo + kO(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 searchPainter's PartitionBinary search on max load — painters_needed(cap) ≤ k → go leftO(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 searchAggressive CowsBinary search on distance — sort; can_place(d) → ans = d, go rightO(n log n + n log range)O(1) extraForgetting 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 searchBook Allocation ProblemBinary search on max pages — m > n → −1; first cap in [max, Σ] with students(cap) ≤ mO(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 searchFind Peak ElementBinary search on slope — nums[mid] < nums[mid+1] → lo = mid + 1 else hi = midO(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 searchMedian of 2 Sorted ArraysBinary search the partition — search c1 in smaller array; valid when l1 ≤ r2 and l2 ≤ r1O(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 searchKth Element of 2 Sorted ArraysBinary 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 searchMinimize Max Distance to Gas StationBinary search on the answer (reals) — need(d) = Σ (⌈g/d⌉ − 1) ≤ k → hi = d else lo = d; 100 iterationsO(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 searchSplit Array — Largest SumBinary search on largest sum — parts(cap) ≤ k → go leftO(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 searchFind Row with Maximum 1'sLower bound per row — ones = m − first index of 1O(n log m)O(1)≥ on tie → returns the last tied row.
Binary searchSearch in a 2D MatrixFlattened binary search — idx → (idx / m, idx % m)O(log(n · m))O(1)mid / n instead of mid / m (divide by column count).
Binary searchSearch in 2D Matrix IIStaircase from top-right — v > target → col − 1; v < target → row + 1O(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 searchFind Peak Element IIBinary search on columns — r = argmax column mid; compare with left/rightO(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 searchMatrix MedianBinary search on value — first x with Σ upper_bound(row, x) > nm/2O(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 mediumRemove Outermost ParenthesesDepth counter — drop ( at depth 0 and ) back to depth 0O(n)O(n) outputChecking 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 mediumMaximum Nesting Depth of the ParenthesesRunning 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 mediumRoman to IntegerSubtract if smaller than the next — v < next → total −= v else total += vO(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 mediumString to Integer (atoi)Iterative with pre-multiply overflow guard — if res > (MAX − d) / 10 → clampO(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 mediumCount Substrings with Exactly K Distinct CharactersatMost(k) − atMost(k − 1) — window counts substrings with ≤ k distinct; subtractO(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 mediumLongest Palindromic SubstringExpand 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 mediumSum of Beauty of All SubstringsIncremental counts per start — fix i; extend j, cnt[s[j]]++, add max − min of non-zero countsO(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
RecursionPow(x, n)Iterative binary exponentiation — walk the bits of n; square x each step, multiply when the bit is setO(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
RecursionGenerate ParenthesesBacktracking on open/close counts — '(' if open < n; ')' if close < openO(4ⁿ / √n)O(n) recursion + outputAllowing ) 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
RecursionPower SetPick / not-pick recursion — at index i: recurse without nums[i], then with itO(n · 2ⁿ)O(n) recursionAppending 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
RecursionCount Good NumbersFast modular power — pow(5, ⌈n/2⌉) · pow(4, ⌊n/2⌋) mod pO(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
RecursionReverse a StackRecursion with insert-at-bottom — pop top, reverse rest, insert top at bottomO(n²)O(n) call stackPushing 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
RecursionCheck if There Exists a Subsequence with Sum K1D subset-sum DP — can[s] | = can[s − x], s from k down to xO(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
RecursionCount All Subsequences with Sum K1D counting DP — ways[s] += ways[s − x], s from k down to xO(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
RecursionGenerate Binary Strings Without Consecutive 1sBacktracking with last-char check — always try 0; try 1 only if the previous char is 0O(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
RecursionCombination SumLoop-based backtracking (sorted, with break) — for j in [start, n): take c[j], recurse from jO(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
RecursionCombination Sum IILoop backtracking with sibling skip — sort; skip c[j] == c[j−1] when j > start; recurse j + 1O(2ⁿ · n) worstO(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
RecursionSubsets 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 + outputDropping 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,
RecursionSubsets IILoop backtracking, record every node — record cur; for j ≥ i: skip equal siblings, push, recurse j + 1O(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
RecursionCombination Sum IIIBacktracking in increasing order — for d in start..9: if d > rem break; push; recurse d + 1O(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
RecursionLetter Combinations of a Phone NumberBacktracking per digit — go(i): for ch in map[digits[i]]: push, go(i + 1), popO(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
RecursionPalindrome PartitioningBacktracking + palindrome table — isPal[i][j] DP, then the same backtracking with O(1) checksO(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
RecursionWord SearchDFS marking the board in place — board[r][c] = '#' during the visit, restore afterO(m·n·3^L)O(L) recursionNot 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
RecursionN-QueensRow 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
RecursionRat in a MazeDFS in D, L, R, U order — direction arrays in alphabetical order → sorted outputO(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
RecursionM-Coloring ProblemBacktracking vertex by vertex — for colour c in 1..m: if safe(v, c) → assign, recurse, undoO(mⁿ) worstO(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
RecursionSudoku SolverBacktracking with constraint tables — row/col/box used-digit tables; recurse over the list of empty cellsO(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
RecursionExpression Add OperatorsBacktracking 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
RecursionSort a stack using recursionPure recursion (sort + insertSorted) — pop x, sort rest, insert x in placeO(n²)O(n) call stackUsing 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 listTraversal in Linked ListIterative walk — cur = head; while cur: visit; cur = cur.nextO(n)O(1) extraMoving 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 listDeletion of the Head of LLAdvance the head — tmp = head; head = head.next; free tmpO(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 listDeletion of the Tail of LLWalk to the second-last node — while cur.next.next: cur = cur.next; cur.next = nullO(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 listDeletion of the Kth Element of LLDummy node — dummy → head; step k − 1 from dummy; bypassO(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 listDelete the Element with Value XDummy + search predecessor — prev from dummy until prev.next.val == x; bypassO(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 listInsertion at the Head of LLNew node points at old head — node(x).next = head; return nodeO(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 listInsertion at the Tail of LLWalk 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 listInsertion at the Kth Position of LLDummy + splice — step k − 1 from dummy; node.next = prev.next; prev.next = nodeO(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 listInsertion Before the Value X in LLDummy + search predecessor — prev.next.val == x → spliceO(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 listFind the Length of the Linked ListIterative count — cnt++ per nodeO(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 listSearch in Linked ListLinear scan — return true on matchO(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 listConvert Array to DLLTail pointer — node(prev = tail); tail.next = node; tail = nodeO(n)O(n) outputSetting 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 listDelete Head of DLLAdvance + clear prev — head = head.next; head.prev = nullO(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 listDelete Tail of DLLWalk to tail, cut via prev — tail.prev.next = nullO(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 listDelete Kth Element of DLLLocate + unlink — fix prev.next and next.prev, each if presentO(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 listRemoving Given Node in DLLRewire 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 listInsert Node Before Head in DLLLink both ways — node.next = head; head.prev = nodeO(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 listInsert Node Before Tail in DLLWalk to tail + insert before — node(next = t, prev = t.prev); fix both neighboursO(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 listInsert Node Before Kth Node in DLLLocate 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 listInsert Before Given Node in DLLSplice between prev and node — 4 link updatesO(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 listReverse a Doubly Linked ListSwap prev/next in place — swap; advance via cur.prev; last visited = headO(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 listAdd Two Numbers in LLSimultaneous 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 listSegregate Odd and Even Nodes in LLWeave two chains — odd/even pointers leapfrog; odd.next = evenHeadO(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 listSort a LL of 0's, 1's and 2'sThree chains — append to zero/one/two dummies; join; cut tailO(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 listRemove Nth Node from the Back of the LLOne pass, gap of n — fast n ahead; move both until fast.next is nullO(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 listReverse a LLIterative three pointers — nxt = cur.next; cur.next = prev; prev, cur = cur, nxtO(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 listAdd One to a Number Represented by LLRightmost non-9 — find last digit ≠ 9; ++ it; zero the restO(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 listFind Middle of Linked ListTortoise and hare — slow += 1, fast += 2 while fast and fast.nextO(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 listDelete the Middle Node in LLFast with a head start — slow = head, fast = head.next.next; bypass slow.nextO(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 listCheck if LL is Palindrome or NotReverse second half — first middle → reverse after it → compare → restoreO(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 listFind the Intersection Point of Y LLPointer switching — p = p.next or headB; q = q.next or headA; until p is qO(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 listDetect a Loop in LLFloyd tortoise and hare — slow 1, fast 2; meet → cycleO(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 listFind the Starting Point in LLFloyd + reset to head — meet; p = head; step both by 1 until equalO(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 listLength of Loop in LLFloyd + one lap — meet; walk until back at meeting pointO(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 listReverse LL in Group of Given Size KIterative with k-th node finder — kth = walk k−1; detach; reverse; reconnectO(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 listRotate a LLRing and cut — tail.next = head; walk n − k%n − 1; cutO(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 listMerge Two Sorted ListsDummy + tail splice — attach smaller; advance; append leftoverO(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 listFlattening of LLRecursive merge from the right — head.next = flatten(head.next); merge(head, head.next)O(N · k)O(k) stackLeaving 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 listSort LLTop-down merge sort — split at first middle; sort; mergeO(n log n)O(log n) stackSecond 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 listClone a LL with Random and Next PointerInterleave, wire random, unweave — A→A'→B→B'; A'.random = A.random.next; splitO(n)O(1) extraSetting 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 listDelete All Occurrences of a Key in DLLIn-place unlink — match → link prev ⇄ next; move head if neededO(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 listRemove Duplicates from Sorted DLLSkip equal run — nxt = first node with different value; relinkO(n)O(1)Forgetting nxt.prev = cur.One pass, two pointers. Same as LC 83 plus the prev fix-up.
Linked listFind Pairs with Given Sum in DLLTwo pointers from both ends — sum < t → left++; > t → right--; = → record, move bothO(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 manipulationCheck if the i-th Bit is SetLeft-shift mask — n & (1 << k) != 0O(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 manipulationCheck if a Number is OddAND with 1 — n & 1O(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 manipulationCheck if a Number is Power of 2n & (n − 1) — one set bit ⇔ clearing it gives 0O(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 manipulationCount the Number of Set BitsBrian Kernighan — n &= n − 1 until 0O(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 manipulationSet the Rightmost Unset Bitn — (n + 1) | +1 carries through trailing 1s into the lowest 0O(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 manipulationSwap Two NumbersXOR swap — a ^= b; b ^= a; a ^= bO(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 manipulationMinimum Bit Flips to Convert NumberXOR + 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 manipulationSingle Number IXOR everything — pairs cancelO(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 manipulationSingle Number IIones / twos state machine — ones = (ones ^ x) & ~twos; twos = (twos ^ x) & ~onesO(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 manipulationSingle Number IIIXOR + split on lowest differing bit — x = a ^ b; low = x & −x; XOR each halfO(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 manipulationDivide Two IntegersShift and subtract — subtract the biggest divisor·2ᵏ that fitsO(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 manipulationPower Set (Bit Manipulation)Bitmask enumeration — for mask in 0…2ⁿ−1, include nums[i] if bit i setO(n·2ⁿ)O(n·2ⁿ) output1 << 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 manipulationXOR of Numbers in a Given RangePrefix XOR f(R) ^ f(L − 1) — f(n) by n mod 4O(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 algorithmsAssign CookiesSort + two pointers — advance cookie always, child when fedO(n log n + m log m)O(1) extraAdvancing 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 algorithmsLemonade ChangeCounters with greedy change — track #5 and #10; for 20 use 10+5 firstO(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 algorithmsFractional KnapsackSort by ratio, fill greedily — best v/w first; last item fractionalO(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 algorithmsJump Game IGreedy 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 algorithmsShortest Job FirstSort + running time — sort; wait += elapsed; elapsed += bO(n log n)O(1) extraAdding 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 algorithmsJob Sequencing ProblemDeadline sort + min-heap — keep the best ≤ d jobs in a heapO(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 algorithmsN Meetings in One RoomSort by end, pick compatible — if start > lastEnd: take itO(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 algorithmsNon-overlapping IntervalsSort by end, count keepers — keep if start ≥ lastEnd; answer n − keptO(n log n)O(1) extraInitialising 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 algorithmsInsert IntervalThree-phase scan — copy left · absorb overlaps · copy rightO(n)O(n) outputUsing ≤ 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 algorithmsMerge IntervalsSort + single pass — if start ≤ last.end: extend, else pushO(n log n)O(n) outputout[-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 algorithmsMinimum Number of PlatformsSorted events, two pointers — if arr[i] ≤ dep[j]: +1 else −1O(n log n)O(1) extraUsing < 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 algorithmsValid Parenthesis StringGreedy balance range — lo/hi of possible open countsO(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 algorithmsCandySlope counting, O(1) space — sum peaks and valleys as trianglesO(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 algorithmsJump Game IIGreedy 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 algorithmsMinimum coins (greedy, canonical denominations)Greedy with division — take V // c copies of each coinO(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 pointerMaximum Points You Can Obtain from CardsSlide the split — start with k left cards, swap one left for one right k timesO(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 pointerLongest Substring Without Repeating CharactersWindow 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 pointerMax Consecutive Ones IIINon-shrinking window — if zeros > k: move l onceO(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 pointerFruit Into BasketsWindow with counts — shrink while > 2 keysO(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 pointerLongest Substring With At Most K Distinct CharactersWindow with counts and a distinct counter — shrink while distinct > kO(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 pointerLongest Repeating Character ReplacementWindow with a stale maxFreq — maxFreq only increases; shrink by oneO(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 pointerMinimum Window SubstringWindow 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 pointerMinimum Window SubsequenceForward match + backward shrink — find an end, walk back to the tightest startO(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 pointerNumber of Substrings Containing All Three CharactersLast-seen positions — add 1 + min(last) per right endO(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 pointerBinary Subarrays With SumatMost(goal) − atMost(goal − 1) — two at-most windowsO(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 pointerCount Number of Nice SubarraysatMost(k) − atMost(k − 1) — window on the odd countO(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 pointerSubarrays with K Different IntegersatMost(k) − atMost(k − 1) — two at-most-distinct windowsO(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 queuesImplement Stack using ArraysGrowable array (capacity doubling) — when full, copy into an array twice the sizeO(1) amortisedO(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 queuesImplement Queue using ArraysCircular buffer (with doubling) — front + count, indices mod capO(1) amortisedO(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 queuesImplement Stack using QueueOne queue, rotate on push — enqueue x, then cycle size−1 elements behind itpush 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 queuesImplement Queue using StackTwo stacks, lazy transfer — pour in → out only when out is emptyO(1) amortisedO(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 queuesImplement stack using LinkedlistHead = top — push: new node → old head; pop: head = head.nextO(1) per opO(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 queuesImplement queue using LinkedlistHead = front, tail = back — enqueue: tail.next = node; dequeue: head = head.nextO(1) per opO(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 queuesBalanced ParanthesisStack of openers — push openers; closer must match the topO(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 queuesInfix to Postfix ConversionShunting-yard (operator stack) — pop while top binds tighter, then pushO(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 queuesInfix to Prefix ConversionReverse, convert, reverse — mirror the string, postfix with flipped ties, mirror backO(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 queuesPrefix to Infix ConversionOperand stack — scan right to left; operator combines the top twoO(n²) strings · O(n) with a treeO(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 queuesPrefix to Postfix ConversionOperand stack — scan right to left; operator combines the top twoO(n²) strings · O(n) with a treeO(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 queuesPostfix to Infix ConversionOperand stack — scan left to right; operator combines the top twoO(n²) strings · O(n) with a treeO(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 queuesPostfix to Prefix ConversionOperand stack — scan left to right; operator combines the top twoO(n²) strings · O(n) with a treeO(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 queuesNext Greater ElementMonotonic stack, right to left — pop ≤ current, top is the answer, push currentO(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 queuesNext Greater Element - 2Monotonic stack over 2n — right-to-left from 2n−1, answer only for i < nO(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 queuesAsteroid CollisionStack of survivors — new left-mover fights right-moving topsO(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 queuesSum of Subarray MinimumsContribution 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 queuesSum of Subarray RangesΣ max − Σ min via monotonic stacks — contribution as max minus contribution as minO(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 queuesRemove K DigitsMonotonic stack — pop larger tops while k > 0, then trimO(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 queuesNext Smaller ElementMonotonic stack, right to left — pop ≥ current, top is the answer, pushO(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 queuesImplement Min StackSingle stack + encoded values — push 2x − min when x is a new minO(1) all opsO(1) extra beyond the valuesSeparate 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 queuesSliding Window MaximumMonotonic deque of indices — pop expired front, pop smaller back, push, read frontO(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 queuesTrapping RainwaterTwo pointers — move the lower side; its running max decides its waterO(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 queuesLargest rectangle in a histogramOne pass, compute on pop — sentinel 0 at the end; area when a bar is poppedO(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 queuesMaximum RectanglesHistogram per row + monotonic stack — update heights, run largest-rectangle per rowO(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 queuesStock span problemStack of (price, span) — pop ≤ price, add their spansO(1) amortisedO(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 queuesThe Celebrity ProblemSingle-candidate elimination — candidate = i whenever candidate knows i; then verifyO(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 queuesLRU CacheHashmap + doubly linked list — map key → node; DLL head = most recentO(1) per opO(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 queuesLFU CacheFrequency buckets + minFreq — freq → ordered set of keys; evict LRU of minFreqO(1) per opO(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 queuesNumber of Greater Elements to the RightMerge-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 treesInorder TraversalIterative with explicit stack — push left spine; pop → visit → go rightO(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 treesPreorder TraversalIterative stack — pop → visit → push right, push leftO(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 treesPostorder TraversalOne stack + last visited — descend left; at top: go right unless right is done; else visitO(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 treesLevel Order TraversalBFS with level snapshot — for _ in range(len(q)): pop, record, push childrenO(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 treesPre, Post, Inorder in one traversalStack of (node, state) — state 1 pre→left · 2 in→right · 3 post→popO(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 treesMaximum Depth in BTRecursive 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 treesCheck if two trees are identical or notRecursive lock-step — null checks, value check, recurse both sidesO(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 treesCheck for balanced binary treeBottom-up height with −1 sentinel — h = −1 if a child is −1 or | hl − hr | > 1O(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 treesDiameter of Binary TreeSingle 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 treesMaximum path sumSingle 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 treesCheck for symmetrical BTsRecursive 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 treesChildren Sum Property in Binary TreePush down, sum up — pre: if childSum < val → children = val else val = childSum; post: val = L + RO(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 treesZig Zag Traversal Of Binary TreeBFS + index placement — lvl[i] or lvl[size−1−i] depending on directionO(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 treesBoundary Traversal of a Binary TreeLeft edge + leaves + reversed right edge — three loops, leaves via DFSO(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 treesVertical Order TraversalCollect triples + one sort — (col, row, val) for every node, sort, group by colO(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 treesTop View of Binary TreeBFS + first-seen per HD — queue of (node, hd); record if hd unseenO(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 treesBottom view of Binary TreeBFS + overwrite per HD — queue of (node, hd); seen[hd] = val every timeO(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 treesRight/Left View of Binary TreeDFS: 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 treesPrint root to node path in BTDFS + backtracking — append; if leaf copy; recurse; popO(n·h) (copies at leaves)O(h) + outputAppending 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 treesLCA in BTSingle postorder — if n in {p,q,null} return n; L,R; both → n else L or RO(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 treesMaximum width of a Binary TreeBFS + normalised heap index — idx -= first of level; children 2i+1, 2i+2O(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 treesPrint all the Nodes at a distance of K in a BTParent 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 treesMinimum time taken to burn the BT from a given NodeParent map + BFS — find start + parents, BFS over {L, R, parent} counting roundsO(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 treesCount total Nodes in a COMPLETE BTLeft/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 treesFlatten Binary Tree to LinkedListMorris-style rewiring — pred = rightmost(left); pred.right = cur.right; cur.right = cur.left; cur.left = nullO(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 treesRequirements needed to construct a unique BTCase check — exactly one is inorder and they differO(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 treesConstruct a BT from Preorder and InorderBounds + 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 treesConstruct a BT from Postorder and InorderBounds + hash map — root = post[pR]; left size = k − iLO(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 treesSerialize and De-serialize BTLevel order with '#' — BFS writes every child slot; decoder BFS pops two tokens per nodeO(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 treesMorris Inorder TraversalMorris inorder — no left → visit, go right; else find pred: no thread → make it, go left; thread → cut, visit, go rightO(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 treesMorris Preorder TraversalMorris preorder — no left → visit, right; pred unthreaded → visit, thread, left; threaded → cut, rightO(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 treesSearch in BSTIterative walk — while cur and cur.val != val: step left/rightO(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 treesFloor and Ceil in a BSTSingle walk per side — right-step → floor candidate; left-step → ceil candidateO(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 treesMinimum and Maximum in BSTSpine walks — leftmost = min, rightmost = maxO(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 treesInsert a given node in BSTIterative — walk until the needed child is null, attachO(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 treesDelete a node in BSTIterative, 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 treesKth Smallest and Largest element in BSTIterative inorder, early stop — kth pop of inorder; kth pop of reverse inorderO(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 treesCheck if a tree is a BST or notBounds recursion — valid(n, lo, hi): lo < n.val < hi, recurse with narrowed windowO(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 treesLCA in BSTIterative split — loop until p and q fall on different sidesO(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 treesConstruct a BST from a preorder traversalUpper-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 treesInorder successor and predecessor in BSTTwo candidate walks — succ: go left → record; pred: go right → recordO(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 treesBST iteratorStack of left spine — push left spine; next = pop + push left spine of rightO(1) amortisedO(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 treesTwo sum in BSTTwo BST iterators — lo = next(), hi = before(); move the side that fixes the sumO(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 treesCorrect BST with two nodes swappedInorder, track first/last violation — on prev > cur: first ← prev (once), last ← curO(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 treesLargest BST in Binary TreePost-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
HeapsHeapify AlgorithmSift up or sift down from ind — smaller → bubble up; larger → sinkO(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.
HeapsBuild heap from a given ArrayBottom-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.
HeapsImplement Min HeapBinary heap on an array — append+siftUp · swap last to root+siftDownpush/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
HeapsImplement Max HeapBinary 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.
HeapsCheck if an array represents a min heapLoop over internal nodes — for i < n/2: check both childrenO(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).
HeapsConvert Min Heap to Max HeapBottom-up max-heapify — for i = n/2−1 … 0: siftDown toward the larger childO(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).
HeapsHeap SortIn-place heap sort — max-heapify; swap root to end; shrink; sift downO(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,
HeapsK-th Largest element in an arrayQuickselect (3-way partition) — partition around pivot; recurse into the side holding index n−kO(n) expectedO(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).
HeapsKth largest element in a stream of running integersMin-heap of size k — push; pop while size > k; return rootadd 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
HeapsSort K sorted arrayMin-heap of size k+1 — seed k+1; pop min to output, push nextO(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
HeapsMerge K sorted ListsMin-heap of heads — pop smallest head, append, push its nextO(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,
HeapsReplace elements by its rank in the arraySort distinct values + hash map — rank[v] = index in sorted(set(arr)) + 1O(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).
HeapsTask SchedulerCounting 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:
HeapsHand of StraightsSorted distinct keys, batch groups — for x ascending: open c[x] groups at xO(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).
HeapsDesign twitterHeap-based k-way merge — max-heap of (time, user, idx); pop ≤ 10, push predecessorfeed 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
HeapsMinimum cost to connect sticksMin-heap greedy — pop two smallest, add cost, push sumO(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
HeapsMaximum Sum CombinationMax-heap best-first + visited — pop (i,j); push (i+1,j), (i,j+1) if unseenO(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
HeapsFind Median from Data StreamTwo 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
HeapsTop K Frequent ElementsBucket sort by frequency — bucket[count] = values; scan from n downO(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
GraphsTraversal TechniquesBFS + iterative DFS — explicit stack, push neighbours reversed, mark on popO(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,
GraphsConnected ComponentsAdjacency list + BFS — build lists; BFS from each unvisited nodeO(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
GraphsNumber of provincesDFS on the matrix — for each unvisited city, DFS scanning its rowO(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
GraphsNumber of islandsBFS flood — queue per island, mark when pushedO(m·n)O(min(m, n)) queueChecking 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
GraphsFlood fill algorithmRecursive DFS — repaint, recurse on same-colour neighboursO(m·n)O(m·n) recursionMissing 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.
GraphsNumber of enclavesMulti-source BFS from the border — flood from border land; count the restO(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.
GraphsRotten OrangesMulti-source BFS — queue all rotten at t = 0; process level by levelO(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
GraphsDistance of nearest cell having oneMulti-source BFS — seed all 1s with distance 0O(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
GraphsSurrounded RegionsMark from the border — border O → '#', flood; then O→X, #→OO(m·n)O(m·n) stackFlipping 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.
GraphsNumber of distinct islandsRelative coordinates — store (r − r0, c − c0) of every cell in DFS orderO(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
GraphsDetect a cycle in an undirected graphDFS with parent — dfs(u, p): visited neighbour ≠ p ⇒ cycleO(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
GraphsBipartite graphBFS colouring — queue; neighbour gets the opposite colourO(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
GraphsTopological sort or Kahn's algorithmKahn's algorithm (BFS on in-degrees) — queue of in-degree-0 nodes; decrement neighboursO(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
GraphsDetect a cycle in a directed graphKahn's algorithm — cycle iff fewer than V nodes get processedO(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.
GraphsFind eventual safe statesKahn on the reversed graph — reverse edges, peel out-degree-0 nodesO(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
GraphsCourse Schedule IKahn'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.
GraphsCourse Schedule IIKahn's algorithm — pop in-degree-0 courses in orderO(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.
GraphsAlien dictionaryAdjacent pairs + Kahn — first mismatch of neighbours → edge; Kahn on k lettersO(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
GraphsShortest path in DAGTopological order + relaxation — Kahn order; relax out-edges onceO(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
GraphsShortest path in undirected graph with unit weightsBFS — dist set at discovery is finalO(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).
GraphsWord ladder IBFS with on-the-fly neighbours — try 26 letters per position; remove from set when queuedO(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
GraphsWord ladder IIBFS depth map + backtracking — depth per word, then DFS back from endO(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
GraphsDijkstra's algorithmMin-heap with lazy deletion — pop smallest (d, u); skip stale; relaxO((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
GraphsPrint shortest pathDijkstra with parent pointers — parent[v] = u on every improvement; walk back from nO((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.
GraphsShortest distance in a binary mazeBFS — distance grid; first discovery is finalO(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.
GraphsPath with minimum effortDijkstra on max-step — heap of (effort, r, c); relax with maxO(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
GraphsCheapest flights within K stopsBellman-Ford with k + 1 rounds — relax every edge from the previous round's snapshotO(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
GraphsMinimum multiplications to reach endBFS 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
GraphsNumber of ways to arrive at destinationDijkstra 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
GraphsBellman-Ford algorithmBellman-Ford (V − 1 rounds + check) — relax all edges V−1 times; one more improving pass ⇒ negative cycleO(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
GraphsFloyd Warshall algorithmFloyd-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) extraPutting 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
GraphsFind the city with the smallest number of neighbors at a threshold distanceFloyd-Warshall + count — all-pairs matrix, then count per rowO(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
GraphsNetwork delay timeDijkstra — heap from k; answer = max distO(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.
GraphsSwim in rising waterMin-heap flood (Dijkstra) — always expand the lowest reachable cell; track the max so farO(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
GraphsDisjoint Set (Union-Find)Union by size + path compression — smaller root under larger; find flattens the pathO(α(n)) amortisedO(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
GraphsFind the MST weightKruskal's algorithm — sort edges by weight; accept an edge if DSU says its ends differO(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
GraphsNumber of operations to make network connectedDSU — union every cable; components = n − successful unionsO(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
GraphsAccounts mergeDSU on account indices — email → first owner; union owners; group emails by rootO(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
GraphsNumber of islands IIOnline DSU — new cell +1; each union with a distinct neighbour −1O(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.
GraphsMaking a large islandDSU sizes + distinct neighbour roots — union all land; each 0 scores 1 + Σ distinct neighbour sizesO(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
GraphsMost stones removed with same row or columnDSU on row and column nodes — union(row x, col y + OFFSET) per stone; count roots among used nodesO(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
GraphsKosaraju's algorithmKosaraju (two DFS passes) — DFS for finish order; DFS on reversed graph in reverse finish orderO(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 /
GraphsBridges in graphTarjan 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
GraphsArticulation point in graphTarjan tin / low — non-root: low[child] ≥ tin[u]; root: ≥ 2 childrenO(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 programmingClimbing stairsTabulation with two variables — iterate bottom-up keeping prev2, prev1O(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 programmingFrog JumpTabulation, O(1) space — keep dp[i−1], dp[i−2] onlyO(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 programmingFrog jump with K distancesTabulation — fill dp left to rightO(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 programmingMaximum sum of non adjacent elementsSpace-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 programmingHouse robberTwo passes by index range — same, without copyingO(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 programmingNinja's trainingTabulation with one row — prev[t] = best ending with t yesterdayO(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 programmingGrid unique paths1D 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 programmingUnique paths II1D 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 programmingMinimum Falling Path SumRow-by-row tabulation — prev row → cur rowO(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 programmingTriangleBottom-up with one row — dp = last row; move upO(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 programmingCherry pickup IIBottom-up with a 2D layer — front[c1][c2] from the row belowO(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 programmingCount Square Submatrices with All OnesDP on the bottom-right corner — dp = 1 + min(up, left, diag); sum dpO(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 programmingBest time to buy and sell stockRunning minimum — profit = price − min so farO(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 programmingBest time to buy and sell stock IITabulated state machine, O(1) — aheadBuy, aheadSell rolled backwardO(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 programmingBest time to buy and sell stock IIIFour forward variables — buy1, sell1, buy2, sell2O(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 programmingBest time to buy and sell stock IVForward buy[]/sell[] arrays — k copies of the Stock III chainO(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 programmingBest time to buy and sell stock with transaction feesForward 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 programmingBest time to buy and sell stock with cooldownBackward tabulation with two look-ahead rows — front1, front2O(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 programmingSubset sum equals to target1D 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 programmingPartition equal subset sum1D boolean DP — dp[t] | = dp[t − x], t descendingO(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 programmingPartition a set into two subsets with minimum absolute sum differenceBoolean row + scan — dp[t] for t ≤ S/2, take the largest trueO(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 programmingCount subsets with sum K1D counting DP — dp[t] += dp[t − x], t descendingO(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 programmingCount partitions with given difference1D 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 programming0 and 1 Knapsack1D 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 programmingMinimum coins1D 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 programmingTarget sumCount subsets with sum (S + target)/2 — reduction + 1D countingO(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 programmingCoin change II1D tabulation, coins outer — dp[t] += dp[t − c], t ascendingO(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 programmingUnbounded knapsack1D 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 programmingRod cutting problemUnbounded knapsack table — items = lengths, capacity = nO(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 programmingLongest increasing subsequenceTails + binary search — lower_bound replace or appendO(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 programmingPrint longest increasing subsequencedp + parent array — parent[i] = best predecessorO(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 programmingLargest divisible subsetSort + LIS-style dp + parent — dp[i] = 1 + max dp[j] with a[i] % a[j] == 0O(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 programmingLongest string chainSort + 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 programmingLongest bitonic subsequenceTwo O(n²) LIS passes — front[i] + back[i] − 1O(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 programmingNumber of longest increasing subsequencesdp + cnt arrays — reset on longer, add on equalO(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 programmingLongest common subsequenceTwo-row tabulation — prev / cur rows over prefixesO(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 programmingLongest common substringEnding-at DP, two rows — match → diag + 1, else 0; track maxO(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 programmingLongest palindromic subsequenceLCS(s, reverse(s)), two rows — reuse LCSO(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 programmingMinimum insertions to make string palindromen − LCS(s, reverse(s)) — reuse LPSO(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 programmingShortest common supersequenceLCS table + backward walk — match → emit once, else emit the dropped charO(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 programmingDistinct subsequences1D DP, j descending — dp[j] += dp[j−1] on matchO(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 programmingEdit distanceTwo-row tabulation — prev / cur with cur[0] = iO(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 programmingWildcard matchingTwo-row tabulation — prev = pattern row i−1O(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 programmingWord breakPrefix DP with hash set — dp[i] | = dp[j] ∧ s[j..i) ∈ setO(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 programmingCount palindromic subsequencesBottom-up interval table — i descending, j ascendingO(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 programmingMatrix chain multiplicationBottom-up interval table — i from n−1 down, j from i+1 upO(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 programmingMinimum cost to cut the stickBottom-up interval table — by increasing gap j − iO(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 programmingBurst balloonsBottom-up interval table — i descending, j ascendingO(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 programmingEvaluate boolean expression to trueBottom-up T / F tables — i descending over symbols, j ascendingO(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 programmingPalindrome partitioning IIFront partition + isPal table — O(1) palindrome lookupsO(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 programmingPartition array for maximum sumBottom-up suffix dp — i from n−1 downO(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 programmingMinimum path sum in a grid1D 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:
TriesImplement Trie (prefix tree)Trie of child arrays — node = children[26] + end flagO(L) per opO(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
TriesImplement Trie II (count and erase)Trie with pass / end counters — pass++ along the path, end++ at the last nodeO(L) per opO(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
TriesLongest word with all prefixes (complete string)Trie: every node on the path is an end — insert all, then walk each word checking endO(Σ 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
TriesNumber of distinct substrings in a stringSuffix trie, count new nodes — for each start i, walk/extend from rootO(n²)O(n² · 26) worstForgetting 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
TriesMaximum XOR of two numbers in an arrayBinary trie, greedy from MSB — insert bits 30..0; query takes the opposite bit when it existsO(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
TriesMaximum XOR with an element from the arrayOffline sort + binary trie sweep — sort queries by m; insert nums ≤ m before answeringO((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 advancedReverse every word in a stringScan from the right — find each word's [j+1, i] going leftwardsO(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 advancedMinimum number of bracket reversals to balance an expressionTwo 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 advancedCount and sayIterative run-length encoding — repeat the encode step n − 1 timesO(Σ 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 advancedRabin-Karp algorithmRabin-Karp rolling hash — O(1) window hash update + verify on matchO(n + m) expected, O(n·m) worstO(1) extraNegative 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 advancedZ-functionLinear 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 advancedKMP 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 advancedShortest palindromeKMP on s#rev(s) — k = lps[-1] = longest palindromic prefixO(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 advancedLongest happy prefixPrefix 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
MathsPrint all primes till NSieve of Eratosthenes — cross out multiples from i², i up to √nO(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
MathsPrime factorisation of a numberSPF 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
MathsCount primes in range L to RSieve + 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
  1. What does each problem entry give?

    Show answer

    Best approach, complexity, the common mistake and what to say in the interview.

  2. 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)
StructureOps
listappend/pop end O(1); insert/pop(0) O(n)
dequeboth ends O(1)
dict/setavg O(1)
heapqpush/pop O(log n), heapify O(n)
sorted + bisectsearch O(log n), insert O(n)
Check yourself 2 questions
  1. Max-heap in Python?

    Show answer

    Push negated values into heapq.

  2. 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#

AlgorithmTimeSpace
Sort (Tim/merge)n log nn
Quick sortn log n avg, n² worstlog n
Heap sortn log n1
Counting / radixn+kk
BFS / DFSV+EV
Dijkstra (heap)(V+E) log VV
Bellman-FordVEV
FloydV³V²
KruskalE log EV
TopoV+EV
Trie insert/searchLΣL
Subsets / perms2^n·n / n!·nn
Check yourself 2 questions
  1. Quick sort worst case?

    Show answer

    O(n²).

  2. 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
  1. Prefix-map seeds: longest versus count?

    Show answer

    Longest uses {0: −1}; count uses {0: 1}.

  2. 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.

No cards match. Try fewer or different words, or press Esc to clear.