Skip to content

Start typing to search patterns, problems and pages.

Cheat sheet

All 20 patterns on one page. Good for the night before an interview.

Foundations

01–06All patterns

Trade memory for instant lookups.

Time
O(n)
Space
O(n)

Reach for it when

  • You check the same values again and again
  • Counts, pairs or duplicates decide the answer
  • Brute force compares every pair of items

Easy ways to go wrong

  • Writing a nested loop before asking what you could store instead.
  • Looking things up in a list, which costs O(n) every time.
  • Using an array as a map key. Turn it into a string or tuple first.

Start from this

// Remember each number and where you saw it.
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
  // What would pair with this number?
  const key = wanted(nums[i]);
  if (seen.has(key)) return [seen.get(key)!, i];
  // Store after the check so it can't match itself.
  seen.set(nums[i], i);
}

Two indices walking toward an answer.

Time
O(n)
Space
O(1)

Reach for it when

  • The input is sorted, or can be sorted first
  • You compare a pair from opposite ends
  • Each step rules out a whole row of options

Easy ways to go wrong

  • Forgetting to sort first when the logic depends on order.
  • Using l <= r when a pair needs two different elements.
  • Not skipping duplicates in problems that ask for unique answers.

Start from this

// Start at both ends of the sorted array.
let l = 0, r = nums.length - 1;
while (l < r) {
  if (isAnswer(l, r)) return [l, r];
  // Each step rules out one end for good.
  if (needBigger(l, r)) l++;
  else r--;
}

A range that grows and shrinks as it scans.

Time
O(n)
Space
O(k)

Reach for it when

  • The answer is a contiguous run (subarray or substring)
  • It asks for the longest, shortest or a count
  • Brute force is two nested loops

Easy ways to go wrong

  • Updating the answer before the window is valid again.
  • Forgetting to remove the left item when you shrink.
  • Using it on a problem with negative numbers, where growing can lower the sum.

Start from this

let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
  // Grow: take in the next item.
  add(s[right]);
  // Shrink from the left until the window is valid.
  while (!valid()) remove(s[left++]);
  // Only count the window once it's valid.
  best = Math.max(best, right - left + 1);
}

Keep running totals, then subtract to get any range.

Time
O(n)
Space
O(n)

Reach for it when

  • You need the sum of many ranges, or of every subarray
  • You count subarrays with a given sum, even with negatives
  • A total minus an earlier total answers the question

Easy ways to go wrong

  • Forgetting to seed the map with 0, which misses every run that starts at index 0.
  • Storing the total before the lookup, which counts an empty run when k is 0.
  • Using a sliding window when the numbers can be negative. The window sum no longer grows as it widens.
  • Taking a remainder of a negative total in JavaScript, which stays negative. Add k and take it again.

Start from this

// How many times each running total has shown up. The empty prefix is 0.
const seen = new Map<number, number>([[0, 1]]);
let prefix = 0;
let answer = 0;
for (const x of nums) {
  prefix += x;
  // A run ending here is good when an earlier total was prefix - k.
  answer += seen.get(prefix - k) ?? 0;
  // Store the total only after the lookup, so a run is never empty.
  seen.set(prefix, (seen.get(prefix) ?? 0) + 1);
}
return answer;

Remember the past, answer on the way back.

Time
O(n)
Space
O(n)

Reach for it when

  • Pairs nest inside each other, like brackets
  • Each item waits for the next bigger one
  • You need to undo steps in reverse order

Easy ways to go wrong

  • Popping from an empty stack. Check it first.
  • Forgetting what’s still on the stack when the loop ends.
  • Storing values when you’ll need indices later.
  • Pushing before popping. Settle the older items first, then push the new one.
  • Getting the order wrong. Decide up front whether the stack rises or falls from bottom to top.

Start from this

// Items still waiting for their answer.
const stack: number[] = [];
for (const x of items) {
  // Pop every item that x settles.
  while (stack.length && shouldPop(stack.at(-1)!, x)) {
    resolve(stack.pop()!, x);
  }
  // x now waits for its own answer.
  stack.push(x);
}

Structures & Recursion

07–12All patterns

Rewire pointers without losing the chain.

Time
O(n)
Space
O(1)

Reach for it when

  • Nodes link onward instead of sitting in a row
  • You rewire links without losing the chain
  • One pass with a few pointers is enough

Easy ways to go wrong

  • Cutting a link before saving the node after it.
  • Skipping the dummy node, then special-casing the head.
  • Reading .next on a node that might be null.

Start from this

// Fake node in front, so the head isn't special.
const dummy = new ListNode(0, head);
let prev = dummy, curr = head;
while (curr) {
  // Save this before rewiring cuts the link.
  const next = curr.next;
  rewire(prev, curr);
  prev = curr;
  curr = next;
}
// The real head, even if the old one moved.
return dummy.next;

Pair simple structures so every call is fast.

Time
O(1)
Space
O(n)

Reach for it when

  • You build a class whose every call must be fast
  • One structure finds, another keeps the order
  • A single array or map answers only half the calls

Easy ways to go wrong

  • Updating one structure and forgetting the other, so the map points at a node the list dropped.
  • Scanning an array to find or remove a value, which makes the call O(n).
  • Skipping the head and tail sentinels, then special-casing the empty list everywhere.

Start from this

class Cache {
  // One structure finds things fast...
  private byKey = new Map<number, Node>();
  // ...and another keeps them in the order you need.
  private order = new DoublyLinkedList();

  use(key: number): void {
    const node = this.byKey.get(key);
    if (!node) return;
    // Every call touches both, in O(1) each.
    this.order.moveToEnd(node);
  }
}

Recursion that follows the branches.

Time
O(n)
Space
O(h)

Reach for it when

  • Data branches into left and right children
  • Answers combine upward from the leaves
  • Each subtree looks like the whole tree

Easy ways to go wrong

  • Leaving out the empty-node base case.
  • Checking a node against its parent only. BST rules cover the whole subtree.
  • Mixing up what a call returns with the answer you’re tracking.

Start from this

function dfs(node: TreeNode | null): number {
  // Empty node: the smallest case, answer it directly.
  if (!node) return 0;
  // Trust each call to solve its own subtree.
  const left = dfs(node.left);
  const right = dfs(node.right);
  // Build this node's answer from its children's.
  return combine(node, left, right);
}

Share prefixes, find words letter by letter.

Time
O(L)
Space
O(total letters)

Reach for it when

  • The task is prefix search or autocomplete
  • Many words share the same beginnings
  • Lookups must cost one step per letter

Easy ways to go wrong

  • Forgetting the end-of-word flag, so “app” matches because “apple” exists.
  • Reaching for a trie when a plain set of words is enough.
  • Not pruning used words in board searches, which repeats the work.

Start from this

let node = root;
for (const ch of word) {
  // Make the path if this letter isn't there yet.
  if (!node.children.has(ch)) {
    node.children.set(ch, new TrieNode());
  }
  node = node.children.get(ch)!;
}
// Without this, "app" matches because of "apple".
node.isWord = true;

Always know the smallest or largest item.

Time
O(log n)
Space
O(n)

Reach for it when

  • You need the k largest or k smallest items
  • Items arrive one at a time and you need the min, max or middle so far
  • Brute force sorts after every arrival

Easy ways to go wrong

  • Using a max-heap for “k largest”. A min-heap of size k is cheaper.
  • Forgetting that Python’s heapq is a min-heap. Negate values for a max-heap.
  • Sorting everything when you only need the top k.

Start from this

// Min-heap: the smallest kept item is on top.
const heap = new MinHeap<number>();
for (const x of nums) {
  heap.push(x);
  // Too many: drop the smallest, keep the k largest.
  if (heap.size() > k) heap.pop();
}
// The top is now the kth largest.
return heap.peek();

Try, recurse, undo.

Time
Exponential
Space
O(depth)

Reach for it when

  • You must list every valid arrangement
  • Each step tries one of a few options
  • A wrong turn can be undone cleanly

Easy ways to go wrong

  • Saving path itself instead of a copy.
  • Forgetting the undo step after the recursive call.
  • Not pruning, so dead branches run all the way down.

Start from this

function dfs(path: number[], start: number) {
  if (isDone(path)) {
    // Save a copy: path keeps changing after this.
    results.push([...path]);
    return;
  }
  for (let i = start; i < choices.length; i++) {
    // Choose.
    path.push(choices[i]);
    // Explore from here. i + 1 uses each choice once; pass i to allow repeats.
    dfs(path, i + 1);
    // Undo, so the next choice starts clean.
    path.pop();
  }
}

Advanced

13–20All patterns

Explore neighbours with BFS and DFS.

Time
O(m·n)
Space
O(m·n)

Reach for it when

  • The input is a grid or a network
  • Answers spread through neighbours
  • You must count joined-up regions
  • You need the fewest moves, and every move costs the same

Easy ways to go wrong

  • Marking a node when you pop it instead of when you push it, so it’s queued twice.
  • Forgetting the graph may have more than one connected piece.
  • Using DFS for a shortest path. BFS finds it when every edge costs the same; different costs need Dijkstra.
  • Counting steps per node popped instead of per layer. Finish the whole layer, then add one.

Start from this

// Mark on push, so no node is queued twice.
const seen = new Set([start]);
const queue = [start];
// Read with an index: shift() is O(n) in JavaScript.
for (let head = 0; head < queue.length; head++) {
  // Oldest first: the closest nodes go first.
  const node = queue[head];
  for (const next of neighbours(node)) {
    if (seen.has(next)) continue;
    seen.add(next);
    queue.push(next);
  }
}

Cheapest paths with Dijkstra, joined groups with Union-Find.

Time
O(E log V)
Space
O(V + E)

Reach for it when

  • Roads have different costs
  • You want the cheapest or fastest route
  • Groups keep merging as links arrive

Easy ways to go wrong

  • Using Dijkstra with negative costs. It assumes a finished node can't get cheaper.
  • Skipping the old-entry check, which redoes work on finished nodes.
  • Reading parent[x] directly. That may not be the leader, so call find(x).
  • Dropping the shortcut in find, which lets long chains slow every lookup.

Start from this

// Dijkstra: the heap hands back the closest node first.
const best = new Array(n).fill(Infinity);
best[start] = 0;
const heap = new MinHeap([[0, start]]);
while (heap.size() > 0) {
  const [time, node] = heap.pop();
  // Old entry: a faster way here was already found.
  if (time > best[node]) continue;
  for (const [next, cost] of roads[node]) {
    // A cheaper way to next? Save it and queue it.
    if (time + cost < best[next]) {
      best[next] = time + cost;
      heap.push([best[next], next]);
    }
  }
}

// Union-Find: each node points toward its group's leader.
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x: number): number => {
  // Point straight at the leader, so the next find is quick.
  if (parent[x] !== x) parent[x] = find(parent[x]);
  return parent[x];
};
// Join two groups. False means they were already one group,
// so this link closes a loop.
const union = (a: number, b: number): boolean => {
  const leaderA = find(a), leaderB = find(b);
  if (leaderA === leaderB) return false;
  parent[leaderB] = leaderA;
  return true;
};

Solve small, remember, build up.

Time
O(n)
Space
O(n)

Reach for it when

  • Today’s answer builds on yesterday’s
  • Brute force retries the same subproblem
  • You only need the last few answers

Easy ways to go wrong

  • Not saying out loud what dp[i] means before coding.
  • Getting the base case wrong, which poisons every later cell.
  • Filling the table in an order where a cell’s inputs aren’t ready yet.

Start from this

// dp[i] is the answer for the first i items.
const dp = new Array(n + 1).fill(0);
// The smallest case, known without any work.
dp[0] = base;
for (let i = 1; i <= n; i++) {
  // Build from answers you already have.
  dp[i] = best(dp[i - 1], fromEarlier(dp, i));
}
return dp[n];

Fill a table cell by cell.

Time
O(m·n)
Space
O(m·n)

Reach for it when

  • Two strings or grids must be compared
  • Each answer builds on smaller prefixes
  • Brute force checks every pair of prefixes

Easy ways to go wrong

  • Off-by-one errors between string indices and table indices.
  • Sharing one row across the table with [[0] * n] * m in Python.
  • Keeping the whole table when two rows would do.

Start from this

// dp[i][j]: answer for first i and first j items.
const dp = Array.from({ length: m + 1 }, () =>
  new Array(n + 1).fill(0));
// Row 0 and column 0 stay as the empty cases.
for (let i = 1; i <= m; i++) {
  for (let j = 1; j <= n; j++) {
    // Each cell reads above, left and diagonal.
    dp[i][j] = combine(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
  }
}
return dp[m][n];

Take the best move now. Never look back.

Time
O(n)
Space
O(1)

Reach for it when

  • A single choice now never needs revisiting
  • Only the best option so far matters
  • Brute force tries every combination

Easy ways to go wrong

  • Trusting a greedy idea without a reason it can’t be beaten.
  • Skipping the sort that makes the local choice safe.
  • Tracking the whole route when one running number would do.

Start from this

// One running value sums up every choice so far.
let state = start;
for (const x of items) {
  // Check you can still go on before choosing.
  if (isStuck(state, x)) return fail;
  // Take the best move now and never look back.
  state = bestChoice(state, x);
}
return state;

Sort by start, then merge or split.

Time
O(n log n)
Space
O(n)

Reach for it when

  • Inputs are ranges with a start and end
  • Overlap or touching decides the answer
  • Order by start, then walk once

Easy ways to go wrong

  • Forgetting to sort first.
  • Replacing the end with the new end. Take the max, since one may contain the other.
  • Deciding whether touching ends count as overlap. Read the problem.
  • Sorting by start when you must remove the fewest. Sort by end, so you keep whichever finishes first.

Start from this

if (intervals.length === 0) return [];
// Sort by start, so overlaps end up side by side.
intervals.sort((a, b) => a[0] - b[0]);
const out = [intervals[0]];
for (const [start, end] of intervals.slice(1)) {
  const last = out[out.length - 1];
  // Overlap: extend the last one to the later end.
  if (start <= last[1]) last[1] = Math.max(last[1], end);
  // No overlap: this one starts a new interval.
  else out.push([start, end]);
}

Walk and transform grids with simple coordinates.

Time
O(m·n)
Space
O(1)

Reach for it when

  • You must change a grid in place
  • The path follows the grid’s shape
  • A formula or flip replaces the simulation

Easy ways to go wrong

  • Dropping the recheck, so a single row or column gets read twice.
  • Mixing up rows and columns on a grid that isn't square.
  • Overwriting a cell you still need. Change the order, or save it first.

Start from this

// Four walls mark what's left to read.
let top = 0, bottom = grid.length - 1;
let left = 0, right = grid[0].length - 1;
while (top <= bottom && left <= right) {
  // Walk one side, then pull that wall in.
  for (let c = left; c <= right; c++) out.push(grid[top][c]);
  top++;
  for (let r = top; r <= bottom; r++) out.push(grid[r][right]);
  right--;
  // Recheck: a single row or column has no way back.
  if (top <= bottom) {
    for (let c = right; c >= left; c--) out.push(grid[bottom][c]);
    bottom--;
  }
  if (left <= right) {
    for (let r = bottom; r >= top; r--) out.push(grid[r][left]);
    left++;
  }
}

// Rotate 90° clockwise: flip across the diagonal, then mirror each row.
for (let r = 0; r < n; r++) {
  for (let c = r + 1; c < n; c++) {
    [grid[r][c], grid[c][r]] = [grid[c][r], grid[r][c]];
  }
}
for (const row of grid) row.reverse();

Use AND, XOR and shifts to work on single bits.

Time
O(k)
Space
O(1)

Reach for it when

  • The problem mentions bits or binary
  • Pairs cancel out (XOR)
  • You can’t use + or extra memory

Easy ways to go wrong

  • Using >> on a negative number in JavaScript. Use >>> to shift in zeros.
  • Forgetting Python ints never overflow. Mask with 0xFFFFFFFF to act like 32 bits.
  • Leaving out brackets. === runs before & in JavaScript, so write (n & 1) === 1.

Start from this

// n & (n - 1) clears the lowest 1 bit.
let count = 0;
while (n !== 0) {
  n &= n - 1;
  count++;
}

// x ^ x is 0, so every pair cancels and the lone value stays.
let lone = 0;
for (const num of nums) lone ^= num;

// Read bit i, set it, or clear it.
const bit = (n >> i) & 1;
n |= 1 << i;
n &= ~(1 << i);