DSA

DSA Patterns — Interview Cheat Sheet

14 essential patterns — recognize the signal, apply the template, solve in 20 minutes.

Interview tip Say the pattern aloud: "Sorted array + pair sum → two pointers from both ends."

① Master pattern table — 14 patterns

#PatternSignalTemplate idea
1Two pointersSorted array, pairs, palindromeLeft/right converge based on condition
2Sliding windowSubarray/substring with constraintExpand R, shrink L while invalid
3Binary searchMonotonic answer spaceMid, discard half where property fails
4Fast & slow pointersLinked list cycle, middleTortoise/hare meet or fast reaches end
5Merge intervalsOverlapping rangesSort by start, merge if overlap
6Cyclic sortArray 1..n, missing/duplicatePlace num at index num-1
7In-place reversalReverse list/subarrayPrev/curr/next pointer swap
8Tree BFSLevel order, shortest path treeQueue level-by-level
9Tree DFSPaths, sums, validate BSTRecursion with state passed down/up
10Two heapsStream median, balanceMax-heap lower half + min-heap upper
11Subsets / backtrackingCombinations, permutationsInclude/exclude each element
12Modified BFSGrid shortest pathQueue + visited matrix + 4/8 dirs
13Topological sortDependencies, prerequisitesKahn indegree zero or DFS post-order
14Dynamic programmingOptimal substructure + overlapDefine state, recurrence, base, order

② Two pointers & sliding window

Sliding window [L ... R]
LwindowR
Two pointers: 3Sum — sort, fix i, two pointers on rest for sum zero. O(n²).

Sliding window: expand R until constraint violated → shrink L until valid → track best. Longest substring without repeat — HashMap of last index. O(n).
Problem typePatternComplexity
Pair sum sortedTwo pointersO(n)
Container most waterTwo pointersO(n)
Min size subarray sum ≥ KSliding windowO(n)
Max in each window of size KDeque monotonic queueO(n)

③ Binary search & monotonic space

Not just sorted arrays: binary search on answer space — e.g. "minimum capacity to ship in D days" where feasible(cap) is monotonic false→true.
  • Identify monotonic predicate can(x) or cannot(x)
  • Lo = min possible, Hi = max possible answer
  • While lo < hi: mid = lo + (hi-lo)/2; shrink range
  • Watch off-by-one: lower vs upper bound variants
ClassicSearch space
Search rotated sorted arrayIndex in array
Koko eating bananasEating speed k
Median of two sorted arraysPartition position

④ Linked list & interval patterns

Fast/slow: cycle detection — if slow meets fast, cycle exists. Find cycle start: reset slow to head, advance both 1 step.

Merge intervals: sort by start; if curr.start ≤ prev.end merge else append new.
In-place list reversal
prev=nullcurr=headnext=curr.nextcurr.next=prev

⑤ Tree patterns — BFS vs DFS

GoalPatternStructure
Level orderBFS queueProcess size at each level
Max depthDFS1 + max(left, right)
Validate BSTDFSPass min/max bounds down
Lowest common ancestorDFSReturn node if match or both subtrees found
Serialize treeBFS or DFS preorderNull markers for reconstruction
BFS = shortest path in unweighted tree/graph. DFS = path enumeration, backtracking on trees.

⑥ Graph — BFS, topo sort, union-find

PatternAlgorithmProblems
Modified BFSQueue + visitedRotting oranges, word ladder, grid islands
Topological sortKahn BFS or DFS post-orderCourse schedule, alien dictionary
Union-FindParent array + rankNumber of provinces, redundant connection
DijkstraMin-heap by distanceWeighted shortest path (non-negative)
Course schedule: build adjacency list + indegree; queue nodes with indegree 0; if processed count < n → cycle.

⑦ Heaps & top-K

Top K largest: min-heap of size K — O(n log K). Top K smallest: max-heap of size K.

Two heaps: max-heap stores lower half, min-heap upper half — median in O(log n) insert.
ProblemHeap typeSize
Kth largest elementMin-heapK
Merge K sorted listsMin-heap of headsK
Find median streamTwo heapsBalanced sizes

⑧ Backtracking & subsets

Template: choose → explore → unchoose. Subsets: at each index include or skip. Permutations: swap or used[] array.
  • Define base case — index == n or path.len == k
  • Prune early if invalid partial state
  • Copy path when adding to result (new ArrayList<>(path))
  • Watch duplicate subsets — sort + skip same value at same depth

⑨ Dynamic programming framework

1. Define state dp[i] or dp[i][j] — what subproblem?
2. Recurrence — how state relates to smaller states
3. Base cases — dp[0], empty string, etc.
4. Order of computation — iterate so dependencies ready
5. Space optimize — rolling array if only dp[i-1] needed
TypeExamplesState
1D linearClimbing stairs, house robberdp[i] best at i
2D gridUnique paths, min path sumdp[r][c]
String DPLCS, edit distancedp[i][j] on prefixes
Knapsack0/1 knapsack, coin changedp[i][w] capacity

⑩ Pattern selection cheat sheet

You see…Reach for…
Sorted + pair/tripletTwo pointers
Contiguous + constraintSliding window
Min/max feasible valueBinary search on answer
Linked list cycle/middleFast/slow pointers
Overlapping intervalsMerge intervals
1..n missing dupCyclic sort
DependenciesTopological sort
Shortest path gridBFS
All combinationsBacktracking
Optimize over choicesDP
two-pointerssliding-windowBFSDFSDPheap