Skip to content

DSA patterns

LeetCode questions by pattern, a cheat sheet, a pattern drill and step-by-step dry runs.

Arrays (4 patterns)

Single Pass Tracking

Keep the best so far, update as you go

Best Time to Buy and Sell Stock, Find Closest Number to Zero, Roman to Integer

Prefix / Suffix

Precompute from left and right, combine

Product of Array Except Self

Sort Then Sweep

Sort first, then compare with neighbour / last kept

Merge Intervals, Rank Transform of an Array, Longest Consecutive Sequence

Matrix

Move boundaries inward, or transform

Spiral Matrix, Rotate Image

Two Pointers (2 patterns)

Opposite Ends

Answer depends on both ends / shrinking range

l = 0, r = n - 1, move inward

while (l < r) {
  sum < target ? l++ : r--
}

Reverse String, Valid Palindrome, Two Sum II - Sorted, 3Sum, Container With Most Water, Trapping Rain Water

Same Direction

One pointer per sequence, move on match

Is Subsequence, Merge Strings Alternately, Longest Common Prefix, Summary Ranges

Sliding Window (3 patterns)

Fixed Size

One enters, one leaves

Maximum Average Subarray I, Permutation in String

Variable: Longest

Expand right, shrink while invalid, record max

Longest Substring Without Repeating Characters, Max Consecutive Ones III, Longest Repeating Character Replacement

Variable: Shortest

Expand until valid, shrink while still valid, record min

Minimum Size Subarray Sum

HashMap / Set (3 patterns)

Frequency Count

Count chars, then compare / consume

Valid Anagram, Maximum Number of Balloons, Group Anagrams

Complement Lookup

Seen before? store value -> index

Two Sum

Seen Sets

One set per group

Valid Sudoku

Stack (2 patterns)

Monotonic Stack

Future element resolves past ones

Daily Temperatures, Next Greater Element I

Auxiliary Stack

Second stack tracks the extra info

Min Stack

Linked List (4 patterns)

Pointer Rewiring

Save next before you break a link

Reverse Linked List, Remove Duplicates from Sorted List, Merge Two Sorted Lists

Fast & Slow / Gap

Cycle, middle, nth from end

slow 1 step, fast 2 steps (or fixed gap)

Linked List Cycle, Middle of the Linked List, Remove Nth Node From End of List

Old -> New Map

Map original node to copy

Copy List with Random Pointer

HashMap + Doubly Linked List

Map for O(1) lookup, list for O(1) order

LRU Cache

Classic

l <= r, mid +- 1

Search Insert Position, Valid Perfect Square, Search a 2D Matrix

First True Boundary

F F F T T T: find the first T

l < r, keep mid with r = mid

First Bad Version, Find Minimum in Rotated Sorted Array, Search in Rotated Sorted Array, Search in Rotated Sorted Array II, Find Peak Element

On Answer

Search the answer range, check feasible

Koko Eating Bananas

Trees (8 patterns)

Postorder: Return Height

Ask children first, return 1 + max(L, R)

Maximum Depth of Binary Tree, Invert Binary Tree, Balanced Binary Tree, Diameter of Binary Tree, Binary Tree Maximum Path Sum

Two Trees Together

Both null true, one null / diff false, recurse &&

Same Tree, Symmetric Tree, Subtree of Another Tree

Carry State Down

Pass state to children, check at leaf

Path Sum

BFS Levels

size = queue.length, process exactly size

Binary Tree Level Order Traversal

BST Inorder = Sorted

Left -> Root -> Right gives ascending

Kth Smallest Element in a BST, Minimum Absolute Difference in BST, Validate Binary Search Tree

BST Direction

Smaller left, bigger right

Lowest Common Ancestor of a BST

Build From Traversals

Preorder gives root, inorder gives sizes

Construct Binary Tree from Preorder and Inorder

Trie

One node per char, mark word end

Implement Trie (Prefix Tree)

Graph (3 patterns)

Grid Flood Fill

2D grid of connected regions

Visit cell, mark it, spread to 4 neighbours

dirs = [[1,0],[-1,0],[0,1],[0,-1]]
dfs(r, c):
  if out of bounds or grid[r][c] !== "1" return
  grid[r][c] = "0"
  for [dr, dc] of dirs: dfs(r + dr, c + dc)

Number of Islands, Rotting Oranges

Topological Sort

Prerequisites / dependency order / cycle in directed graph

Indegree 0 goes first (Kahn BFS)

indeg[v]++ for every edge u -> v
queue = nodes with indeg 0
while queue: u = shift, order.push(u)
  for v of graph[u]: if --indeg[v] === 0 push v

Course Schedule

Dijkstra

Shortest path / minimum cost with weights >= 0

Pop closest, relax neighbours

dist = Infinity, dist[src] = 0
heap = [[0, src]]
while heap:
  [d, u] = popMin()
  if d > dist[u] continue
  for [v, w] of graph[u]
    if d + w < dist[v]: dist[v] = d + w, push([dist[v], v])

Network Delay Time

Heap / Top K (2 patterns)

Size-K Heap

Kth largest / top k / k closest

Min-heap of size k keeps the k largest

Kth Largest Element in an Array, Top K Frequent Elements

K-Way Merge

Heap holds the head of every list

Merge k Sorted Lists

Backtracking (1 pattern)

Choose / Explore / Undo

push, recurse, pop

Subsets, Combination Sum, Permutations

Dynamic Programming (3 patterns)

1D: Previous Steps

dp[i] from dp[i-1], dp[i-2]

Climbing Stairs, House Robber

Unbounded Choices

For each amount, try every option

Coin Change, Word Break

Subsequence

Match -> extend, else best of skipping

Longest Increasing Subsequence, Longest Common Subsequence