Notes
All notes

DSA interview question bank: patterns, not problems

Problem. DSA interviews don’t test 300 problems — they test ~15 patterns wearing different costumes. This bank organizes the questions that actually recur (two pointers, sliding window, backtracking, DP on grids…) by pattern, with the tell that reveals each one, the canonical move, and the complexity. Grounded in a real solved set: 129 accepted problems across arrays, trees, graphs, and DP.

Start here when you’re stuck — most interviews are won by naming the pattern in the first two minutes:

flowchart TD
    S[Read the problem] --> Q1{Pair summing to a target?}
    Q1 -->|unsorted| H[Hash map of complements]
    Q1 -->|sorted| TP[Two pointers inward]
    S --> Q2{Contiguous subarray or substring?}
    Q2 -->|fixed size| W[Sliding window]
    Q2 -->|nested structure| ST[Stack]
    S --> Q3{All subsets or orderings?}
    Q3 -->|yes| BT[Backtracking: choose, recurse, undo]
    S --> Q4{Optimal over prefixes?}
    Q4 -->|yes| DP[DP: define dp-i, find recurrence]
    S --> Q5{Connected regions or levels?}
    Q5 -->|yes| G[Graph BFS or DFS]

Arrays and hashing

1. Two Sum — why is the hash map version O(n)?

One pass: for each x, check whether target - x was seen; if not, store x. Each lookup and insert is \(O(1)\) average, so total time is \(O(n)\) with \(O(n)\) space.

The tell. “Pair” + “unsorted” + “return indices” means complements in a map. If the array were sorted, two pointers from both ends would do it in \(O(1)\) space instead.

2. Group Anagrams — what’s the key?

Sorted word (or 26-count tuple) as the dict key; anagrams collide by construction.

Why it matters. Canonical-form keys generalize: same trick groups isomorphic strings, shifted rows, and duplicate subtrees (serialize the subtree as the key).

3. Product of Array Except Self — no division, O(1) extra space?

Two passes: left products, then right products folded in. Output array doesn’t count toward space.

The pattern. Prefix/suffix decomposition — whenever each answer combines “everything left” with “everything right”, build both passes instead of recomputing. Same shape as trapping rain water (max-left/max-right).

4. Longest Consecutive Sequence in O(n)?

Dump everything in a set; only start counting from numbers with no predecessor (x - 1 absent). Each chain is walked once.

The insight. The set turns “is the neighbor there?” into \(O(1)\), and starting only at chain heads keeps total work linear. Sorting first is the \(O(n \log n)\) trap answer — fine to mention, then beat it.

5. First Missing Positive in O(n) time, O(1) space? (hard, solved)

Use the array itself as the hash table: place each value v (if \(1 \le v \le n\)) at index v - 1 by swapping; then the first index holding the wrong value is the answer.

What it teaches. In-place hashing whenever values are bounded by length (cyclic sort family). Interviewers accept the swap loop once you argue each position settles at most once.

Two pointers and sliding window

6. Container With Most Water — why move the shorter side?

Area is width × min-height. Moving the taller side can only shrink width while the height stays capped by the shorter side; moving the shorter side is the only move that can improve the binding constraint.

Say it in one line. “The shorter line bottlenecks the area, so only moving it can help — every skipped state is provably worse.”

7. Longest Substring Without Repeating Characters?

Sliding window with last-seen positions: expand right; on a repeat, jump left past the previous occurrence. Each index enters and leaves once: \(O(n)\).

\begin{tikzpicture}[
  b/.style={draw,thick,minimum width=0.8cm,minimum height=0.8cm,font=\small\ttfamily}
]
  \foreach \i/\v in {0/a,1/b,2/c,3/a,4/b,5/c,6/b,7/b} {
    \node[b] at (\i*0.85,0) {\v};
  }
  \draw[thick] (1.7,0.65) -- (1.7,0.9) -- (5.1,0.9) -- (5.1,0.65);
  \node[font=\scriptsize] at (3.4,1.25) {window: abc};
\end{tikzpicture}

Template to memorize. The loop below is half of all substring problems — only the “valid?” predicate and the shrink step change:

def longest(s, valid):
    seen, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        seen[ch] = seen.get(ch, 0) + 1
        while not valid(seen):            # shrink until valid again
            seen[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

8. When is binary search the answer even without a sorted array?

Whenever you can test a candidate answer in \(O(n)\) and feasibility is monotone: if x works, everything bigger works (Koko eating bananas, minimum capacity, first bad version).

The reframe. Stop searching the input; search the answer space. lo = impossible, hi = definitely possible, then while lo + 1 < hi. Peak element and first/last position are the same template on disguised arrays.

Stacks

9. Daily Temperatures — why a stack, and monotone in which direction?

Scan while keeping a decreasing stack of indices; when a warmer day arrives, it resolves everyone waiting below it. Each index pushes and pops once: \(O(n)\).

The family. Next greater/smaller element, stock span, largest rectangle in histogram, trapping rain water (two-pointer variant) — all “who is the next element that breaks my order” questions.

10. Evaluate Reverse Polish Notation?

Stack of operands; on an operator, pop two, apply, push back. \(O(n)\) time, \(O(n)\) space.

What it proves. You can execute a grammar with explicit state — the same skill as validating parentheses (Generate Parentheses, Removing Stars) and decoding strings. Mention the two-stack extension for infix (shunting-yard) if they push further.

11. Min Stack with O(1) getMin?

Store pairs (value, min-so-far) — or a parallel min-stack. Every operation stays \(O(1)\) at the cost of one extra number per entry.

Follow-up to expect. “Now pop from the middle” (you can’t — that’s the point of the interface), or Min Queue via two Min Stacks, which tests whether the trick composes.

Linked lists

12. Reverse a linked list — iterative and recursive?

Iterative: prev, curr, rewire curr.next before advancing. Recursive: reverse the rest, then head.next.next = head.

Why they still ask it. It’s the gateway phenotypic test for pointer discipline — Remove Nth From End (two pointers, gap of n), Add Two Numbers (carry loop), and Copy List with Random Pointer (interleave clones) all assume you can rewire without losing the list.

13. Copy List with Random Pointer without extra space?

Three passes, no hash map: clone each node inline (A → A' → B → B'), wire randoms via original.random.next, then unzip.

The lesson. Interleaving buys \(O(1)\) space by borrowing the structure itself as the map — same idea as Morris traversal and the First Missing Positive swap trick above.

14. Merge k Sorted Lists — why a heap? (hard, solved)

Push all heads into a min-heap; repeatedly pop the smallest, append it, push its next. \(O(N \log k)\) for \(N\) total nodes.

The alternative they want compared. Pairwise merging is \(O(Nk)\)-ish without divide and conquer, \(O(N \log k)\) with it — the heap just does the same work with less code. Say both, then write the heap.

Trees and graphs

15. Same Tree vs Right Side View — DFS or BFS?

Same Tree is structural recursion: values equal and both subtrees same (DFS, \(O(n)\)). Right Side View wants the last node per depth — BFS level order taking each level’s tail, or DFS visiting right-first and recording first-seen depths.

The split. “Compare/shape” is DFS; “per-level” is BFS. Lowest Common Ancestor of a BST adds the ordering trick (go left/right by comparison); Count Good Nodes threads a running max down the recursion.

16. Number of Islands — why is it a graph problem?

Grid cells are vertices, adjacency is edges. DFS/BFS from each unvisited land cell, marking visited (mutate in place or a set): each cell processed once, \(O(mn)\) time.

Extensions. Max Area of Island (track sizes), Rotting Oranges (multi-source BFS by minutes = level order), Detonate Bombs (build the directed graph first, then DFS each start). Always state the visited strategy before coding.

17. When is BFS better than DFS?

Shortest path in unweighted graphs (levels = distance), level-order output, and anything where the nearest answer wins. DFS for exhaustive search, connectivity, and topological order.

Memory footnote. BFS holds the frontier (\(O(w)\)), DFS holds the path (\(O(h)\)) — on wide shallow graphs DFS is leaner; say which dominates for the given shape.

Backtracking

18. Subsets, Permutations, Combinations — one template?

Choose, recurse, undo. Subsets decide include/skip per index; permutations decide which remaining element goes next; combinations add a start index so order doesn’t duplicate.

\begin{tikzpicture}[
  n/.style={draw,thick,circle,minimum size=0.85cm,font=\small\ttfamily},
  a/.style={->,thick},
  l/.style={font=\scriptsize}
]
  \node[n] (r) at (0,0) {$\emptyset$};
  \node[n] (a) at (-1.8,-1.5) {1};
  \node[n] (b) at (1.8,-1.5) {$\emptyset$};
  \node[n] (a1) at (-2.7,-3) {12};
  \node[n] (a2) at (-0.9,-3) {1};
  \node[n] (b1) at (0.9,-3) {2};
  \node[n] (b2) at (2.7,-3) {$\emptyset$};
  \draw[a] (r) -- (a) node[midway,left,l] {take};
  \draw[a] (r) -- (b) node[midway,right,l] {skip};
  \draw[a] (a) -- (a1);
  \draw[a] (a) -- (a2);
  \draw[a] (b) -- (b1);
  \draw[a] (b) -- (b2);
\end{tikzpicture}
def subsets(nums):
    out = []
    def dfs(i, path):
        out.append(list(path))      # every node is an answer
        for j in range(i, len(nums)):
            path.append(nums[j])    # choose
            dfs(j + 1, path)
            path.pop()              # undo
    dfs(0, [])
    return out

Complexity honesty. Output itself is \(O(n \cdot 2^n)\) for subsets — say so; the recursion is not the dominant term. Permutations are \(O(n!)\); prune (sort + skip duplicates) for Combination Sum II style variants.

19. Generate Parentheses / Letter Combinations — what’s shared?

Both build strings left to right with validity maintained incrementally: parentheses track (open, close) counts (close only if close < open); phone digits iterate letters per digit.

The principle. Constrain during construction, never generate-and-test — the search tree stays Catalan-sized instead of exponential garbage.

Dynamic programming

20. Climbing Stairs to House Robber to Coin Change — what’s the ladder?

One recurrence family: dp[i] depends on a fixed window of predecessors (dp[i-1] + dp[i-2], max(dp[i-1], dp[i-2] + v), min over coins of dp[i-c] + 1). Space compresses to the window (two variables for stairs).

What to say first. State the subproblem in one sentence (“fewest coins for amount x”), write the recurrence, then the base cases — in that order. If they ask for the actual choices (not just the count), parent-pointer reconstruction beats re-derivation.

21. Unique Paths / grid DP — why iterate, not recurse?

Grid DAG: dp[r][c] = dp[r-1][c] + dp[r][c-1] fills row-major in \(O(mn)\) time, \(O(n)\) space with one rolling row; obstacles zero the cell.

Generalize. 2-D DP is memoization over a DAG — whenever transitions only come from “earlier” cells, iteration order replaces the call stack. Same for Longest Common Subsequence and Edit Distance (diagonal + left + top).

22. Maximum Subarray — Kadane’s in one sentence?

Track the best subarray ending here: extend it or restart at x, whichever is larger; the global best is the max over positions. \(O(n)\) time, \(O(1)\) space.

The trap. Empty-subarray conventions (allow zero or not) — clarify before coding. Jump Game is the same greedy instinct: reachability, not optimality, so track farthest-reachable instead of a table.

Heaps, intervals, bits

23. K Closest Points — why a heap, and of what size?

Max-heap of size k on squared distance: \(O(n \log k)\). Full sort is \(O(n \log n)\) — fine to mention, then beat it; quickselect \(O(n)\) average is the follow-up.

Heap reflex. Top-k anything, merge-k-anything (Merge k Lists above), median streams (two heaps) — whenever the answer is an extreme over a stream, the heap holds exactly k candidates.

24. Merge Intervals / Insert Interval?

Sort by start, then sweep merging overlaps (\(O(n \log n)\)). Insert keeps the non-overlapping prefix/suffix and merges only the middle run.

The pattern. Sort-then-sweep also covers meeting rooms, car pooling (difference array), and erase-overlap-intervals (greedy by end time).

25. Bit tricks worth memorizing?

x & (x-1) clears the lowest set bit (popcount loop, power-of-two test); x & -x isolates it. Single Number is XOR cancellation; Counting Bits is dp[i] = dp[i >> 1] + (i & 1).

When bits appear. Flags, parity, subsets-as-bitmasks (n ≤ 20 BT with bitmask DP), and space-critical counters — otherwise prefer readability.

Complexity cheat sheet

Operation Time Space
Hash insert/lookup \(O(1)\) avg \(O(n)\)
Sort \(O(n \log n)\) \(O(n)\) / \(O(\log n)\)
Binary search \(O(\log n)\) \(O(1)\)
BFS / DFS \(O(V + E)\) frontier / path
Backtracking (subsets) \(O(n \cdot 2^n)\) out \(O(n)\) stack
DP 1-D / grid \(O(n)\) / \(O(mn)\) window / rolling row
Heap push/pop \(O(\log k)\) \(O(k)\)

Edge cases for interview day