Leetcode Problems Cheatsheet

Pattern recognition guide for coding interviews — identify which algorithm or data structure to use based on problem keywords

If the problem says... → Use...

If the problem says...→ Use...
subarray / prefix / in-place / two pointersArrays & Strings
count / frequency / duplicates / anagramHash Table / Counter
next/prev pointer / reverse / cycleLinked List
k-th / top-k / stream median / merge k listsHeap (often 1 or 2 heaps)
shortest path / hops / weighted graphBFS (unweighted) / Dijkstra (pos weights) / Bellman-Ford (neg or "≤k edges")
prereqs / ordering / DAGTopological sort (Kahn)
connected components / provincesUnion-Find (Disjoint Set)
#ways / min cost / max profit / longestDynamic Programming
all combinations / generate all / chooseBacktracking
If the problem says...→ Use...
tree traversal / depth / validate BSTTree recursion / BFS levels
O(log n)Binary Search (templates)
Contiguous subarray/substringSliding Window
Next greater/smaller elementMonotonic Stack
Meetings / Time intervalsSorting + Interval Merge
Prefix / Word searchTrie (Prefix Tree)
Bitwise / Set bitsBit Manipulation
Smallest missing positive / DuplicateCyclic Sort
Find the middle / Cycle detectionFast & Slow Pointers (Tortoise/Hare)

Pattern Deep Dives

Arrays & Strings
  • Two pointers (ends): reverse, palindrome, swap-to-middle
  • Two pointers (slow/fast): remove elements in-place, dedupe
  • Prefix sums: pivot index, subarray sums
⚠️ Compare sums/invariants, not "which pointer seems smaller"
Hash Table
  • Use for: counts, membership, mapping to indices
  • Collision is a detail; your job is using dict/set/Counter effectively.
Linked List
  • Patterns: fast/slow cycle, reverse, swap pairs
⚠️ If you don't sever links, you can create cycles → infinite recursion
Heap
  • Best for: top-k, merge-k, stream median (two heaps)
  • Array index math:
left   = 2*i + 1
right  = 2*i + 2
parent = (i-1) // 2
Trie
  • Node stores "next pointers" + end flag
  • Replace Words pattern:
    1. Build trie from roots
    2. For each word, walk until end==True → replace with that prefix
Trees
  • Pre/In/Post order: (Root-L-R) / (L-Root-R) / (L-R-Root)
  • BFS-level order for depth, layers, shortest path in tree
Graphs
  • BFS: unweighted shortest path
  • DFS: explore / connected components / all paths (careful: "all paths" can blow up)
  • Union-Find: connectivity merges (provinces)
  • Toposort: ordering with prereqs (DAG)
  • Dijkstra vs Bellman-Ford:
    Dijkstra: positive weights
    Bellman-Ford: negative weights or "relax edges with iteration control"; copy trick for "≤k edges"
Sorting (quick memory anchors)
  • Selection: in-place, not stable, O(n²)
  • Bubble: stable, O(n²)
  • Insertion: stable, good for small/nearly-sorted
  • Merge sort: stable, O(n log n), extra O(n)
  • Quick sort: avg O(n log n), worst O(n²), in-place-ish (stack)
  • Counting/Radix/Bucket: special constraints (bounded keys / digit-based / distributions)

Pro-Tip: The 'Constraint' Pattern

Sometimes the pattern isn't in the words, but in the Time Complexity required. Look at the input size constraint to narrow down the approach:

N < 20

Backtracking

Exponential time is acceptable for small N. Think DFS with exploration.

N < 500

O(N³)

Often Floyd-Warshall (all-pairs shortest path) or triple-nested DP.

N < 10⁵

O(N log N) or O(N)

Sorting/Heap for O(N log N), or Two Pointers/Sliding Window/Hash Table for O(N).

N = 10⁹+

O(log N)

Almost always Binary Search. Massive N means you can't iterate linearly.

Quick Reference by Category

Data Structures

Arrays & Strings
Two pointers, sliding window, prefix sums
Hash Table / Counter
Fast lookup, frequency counting
Heap
Top-K, median, merge K sorted
Stack / Queue
Monotonic stack, BFS with queue
Trie
Prefix matching, word search
Union-Find
Connected components, cycle detection

Algorithms

Binary Search
O(log N), sorted arrays, 'minimize maximum'
DFS / BFS
Graph traversal, tree problems, shortest path
Dynamic Programming
'# of ways', 'min/max cost', overlapping subproblems
Backtracking
Generate all combinations, permutations, subsets
Topological Sort
Course schedule, task ordering, DAG
Dijkstra / Bellman-Ford
Weighted shortest path problems

Common Interview Patterns

🔄 Sliding Window

Contiguous subarray/substring with a condition. Move right to expand, left to contract.

👈👉 Two Pointers

Two indices moving through data. Often on sorted arrays or linked lists.

🐢🐇 Fast & Slow

Cycle detection, finding middle element. Tortoise and hare algorithm.

📊 Monotonic Stack

Next/previous greater/smaller element. Stack maintains increasing/decreasing order.

🔀 Merge Intervals

Sort by start time, then merge overlapping intervals. Classic meeting rooms problem.

🔄 Cyclic Sort

Array contains numbers in range [1, N]. Place each number at its correct index.

🌲 Tree DFS Patterns

Preorder, inorder, postorder. Path sums, tree diameter, validate BST.

📈 Prefix Sum

Subarray sum queries in O(1). Build cumulative sum array first.

🎯 Binary Search Variants

'Find first/last', 'minimize maximum', 'maximize minimum'. Master the templates.

Leetcode Problems — pattern recognition for coding interviews