Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

NeetCode Roadmap — Pattern Cheat‑Sheet

Use this as a quick navigator. Tags legend at the top; each problem in the index is mapped to a tag + one‑liner hint.

🔎 Super‑Concise Navigator (read this first)

Signal in Problem Likely Pattern Core Trick Typical Time / Space
“any order”, existence, counts, uniqueness ARR/HASH set / Counter O(n) / O(n)
Sorted input or answer monotonic w.r.t a parameter BS binary search on index/answer O(log n * check)
“find pair/triplet”, sorted or sort‑able TP left/right pointers; shrink window O(n log n) or O(n) / O(1)
“longest/shortest subarray/substring” with constraint SW grow + shrink while invalid O(n) / O(k)
“previous/next greater/smaller”, ranges, histogram MS monotonic stack of indices O(n) / O(n)
Parentheses, editors, evaluation STK push/pop matching or ops O(n) / O(n)
Stream k‑th / median / top‑k / merge k PQ/HEAP min/max heap(s) O(log k) per op
K lists/arrays merging K‑MERGE heap by head elements O(n log k)
Backtracking/combinatorial generation BTK choose/skip; pruning O(b^d) / O(d)
Word prefix / wildcard TRIE trie + DFS/backtrack O(total chars)
Grid islands/regions, shortest paths (unit edges) BFS/DFS flood‑fill; BFS layers O(mn)
DAG ordering / prerequisites TOPO indegree BFS/stack O(V+E)
Graph weighted shortest DIJK PQ Dijkstra O(E log V)
Components / cycles in undirected UF union‑find ~O(α(n))
1‑D DP (linear relation) DP1 prefix/rolling arrays O(n) / O(1..n)
2‑D grid/string DP DP2 table; direction matters O(nm)
Intervals merge/schedule INTV/GREEDY sort by start/end O(n log n)
Bitwise counts/parity BIT bit ops / DP on bits O(n)
Math tricks (pow, reverse, geometry) MATH formulas / overflow care varies

Tags legend: ARR/HASH (Arrays and Hashing), BS (Binary Search), TP (Two Pointers), SW (Sliding Window), MS (Monotonic Stack), STK (Stack), PQ/HEAP (Priority Queue / Heap), K-MERGE (K-way Merge), BTK (Backtracking), TRIE (Trie), BFS/DFS (Graph Traversal), TOPO (Topological Sort), DIJK (Dijkstra's Algorithm), UF (Union-Find), DP1 (1D Dynamic Programming), DP2 (2D Dynamic Programming), INTV/GREEDY (Intervals / Greedy), BIT (Bit Manipulation), MATH (Math).


🧭 How to pick an approach (decision mini‑tree)

  1. Sorted / monotonic? → try BS (on index or answer).
  2. Substring/subarray windowed constraint?SW; if pair/triple sum → TP.
  3. Next/previous greater/smaller / range area?MS.
  4. Parentheses/eval/history?STK.
  5. Top‑k / streaming / median / farthest/closest k?PQ/HEAP.
  6. Explicit “all combos/perms/subsets/paths”?BTK (prune early).
  7. Words prefixes/wildcards?TRIE (+ backtrack).
  8. Tree? → DFS postorder for aggregates; BST invariants for order.
  9. Graph reachability / islands / shortest (unit cost)?BFS/DFS. Weighted shortest → DIJK. Prereqs → TOPO. Components/cycle undirected → UF.
  10. Optimization over sequences/grids with overlapping subproblems?DP1/DP2.
  11. Intervals (merge/schedule/cover)? → sort + INTV/GREEDY.
  12. Bity feel (parity, unique number, Hamming)BIT.

⏱️ Complexity quick rules

  • Loops: nested loops multiply; loop + hash ops is O(n) average.
  • Two pointers / Sliding window: O(n) if each index moves ≤ n times; space O(1) or O(Σ alphabet) for counts.
  • Binary search: O(log range) * cost(check).
  • Recursion: time ≈ nodes visited; space includes recursion depth.
  • Heaps: push/pop O(log k); build‑heap O(n).
  • Graphs: BFS/DFS O(V+E); Dijkstra O(E log V).
  • DP: states × transitions; space often compressible by keeping only needed previous rows/cols.
  • Monotonic stack: each index pushed/popped once → O(n).

🧩 Pattern Playbooks (micro‑templates)

  • Sliding Window (variable size)

    l = 0; need = {...}; have = Counter()
    for r, x in enumerate(s):
        have[x] += 1
        while invalid(have, need):    # shrink to restore constraint
            have[s[l]] -= 1; l += 1
        best = max(best, r-l+1)
  • Two Pointers (sorted sum / container)

    i, j = 0, n-1
    while i < j:
        s = a[i] + a[j]
        if s == T: ...; i += 1; j -= 1
        elif s < T: i += 1
        else: j -= 1
  • Monotonic Stack (next greater / histogram)

    st = []  # store indices with mono property
    for i, x in enumerate(arr + [sentinel]):
        while st and arr[st[-1]] > x:    # or < for increasing
            j = st.pop()
            # compute span/area using i and st[-1]
        st.append(i)
  • Binary Search on Answer

    lo, hi = L, R
    def ok(x): return feasible(x)  # monotone predicate
    while lo < hi:
        mid = (lo+hi)//2
        if ok(mid): hi = mid
        else: lo = mid+1
    return lo
  • Topological Sort (Kahn)

    indeg = [0]*n; adj = ...
    q = deque([v for v in range(n) if indeg[v]==0])
    order = []
    while q:
        v = q.popleft(); order.append(v)
        for u in adj[v]:
            indeg[u]-=1
            if indeg[u]==0: q.append(u)
  • Backtracking skeleton

    res = []
    def dfs(path, i):
        if done(path, i): res.append(path[:]); return
        for choice in choices(i, path):
            if prune(choice, path): continue
            apply(choice); dfs(path, i+step); undo(choice)
    dfs([], start)

📚 Problem → Pattern Index (tags + 1‑liner)

  • Contains Duplicate — ARR/HASH (use set).
  • Valid Anagram — ARR/HASH (count letters or sort).
  • Two Sum — ARR/HASH (map value→index while iterating).
  • Group Anagrams — ARR/HASH (key = sorted or 26‑count tuple).
  • Top K Frequent Elements — PQ/HEAP or BUCKET (freq then heap/buckets).
  • Encode and Decode Strings — ARR/HASH (length‑prefix).
  • Product of Array Except Self — ARR (prefix * suffix; no division).
  • Valid Sudoku — ARR/HASH (row/col/box sets).
  • Longest Consecutive Sequence — ARR/HASH (start only at sequence starts).
  • Valid Palindrome — TP (filter alnum; i/j inward).
  • Two Sum II (sorted) — TP.
  • 3Sum — TP (sort + skip dups + inner 2‑sum).
  • Container With Most Water — TP (move shorter wall).
  • Trapping Rain Water — TP / MS (two‑sided max or stack).
  • Best Time to Buy and Sell Stock — DP1/GREEDY (track min so far).
  • Longest Substring Without Repeating — SW (map char→last index).
  • Longest Replacing Character — SW (max‑freq in window).
  • Permutation in String — SW (fixed window counts).
  • Minimum Window Substring — SW (need vs have; shrink when valid).
  • Sliding Window Maximum — Deque (mono deque of indices).
  • Valid Parentheses — STK (matching pairs).
  • Min Stack — STK (stack of pairs or aux min).
  • Evaluate Reverse Polish Notation — STK (push nums, pop2 for ops).
  • Generate Parentheses — BTK (counts of open/close).
  • Daily Temperatures — MS (next greater index).
  • Car Fleet — GREEDY (sort by pos; stack of arrival times).
  • Largest Rectangle in Histogram — MS (first smaller on both sides).
  • Binary Search — BS (classic).
  • Search a 2D Matrix — BS (flatten or stair search).
  • Koko Eating Bananas — BS‑Answer (hours check).
  • Find Minimum in Rotated Sorted Array — BS (compare mid to right).
  • Search in Rotated Sorted Array — BS (identify sorted half).
  • Time Based Key Value Store — BS (per‑key list; bisect by time).
  • Median of Two Sorted Arrays — BS‑Partition (on smaller array).
  • Reverse Linked List — LL (iterative pointers).
  • Merge Two Sorted Lists — LL (dummy head).
  • Linked List Cycle — LL (Floyd fast/slow).
  • Reorder List — LL (find mid, reverse 2nd, merge).
  • Remove Nth Node From End — LL (two pointers gap k).
  • Copy List With Random Pointer — LL/ARR/HASH (old→new map).
  • Add Two Numbers — LL (carry).
  • Find The Duplicate Number — BS or Cycle (Floyd) (array as next).
  • LRU Cache — DLL + HASH (move to head; evict tail).
  • Merge K Sorted Lists — K‑MERGE (heap of heads).
  • Reverse Nodes in K Group — LL (reverse chunk by chunk).
  • Invert Binary Tree — BT (DFS swap).
  • Maximum Depth of Binary Tree — BT (DFS depth).
  • Diameter of Binary Tree — BT (postorder return height + update best).
  • Balanced Binary Tree — BT (height; -1 sentinel).
  • Same Tree — BT (DFS compare).
  • Subtree of Another Tree — BT (isSame at every node / serialize).
  • LCA of a BST — BST (walk using ordering).
  • Binary Tree Level Order Traversal — BFS (queue).
  • Binary Tree Right Side View — BFS (last per level).
  • Count Good Nodes in Binary Tree — BT (track max on path).
  • Validate BST — BST (min/max bounds).
  • Kth Smallest in BST — BST (inorder count).
  • Construct Tree from Preorder & Inorder — BT (hash pos in inorder).
  • Binary Tree Maximum Path Sum — BT (postorder gain; track global).
  • Serialize & Deserialize Binary Tree — BT (BFS/DFS with nulls).
  • Kth Largest in a Stream — HEAP (min‑heap size k).
  • Last Stone Weight — HEAP (max‑heap).
  • K Closest Points to Origin — HEAP (max‑heap size k) or quickselect.
  • Kth Largest in an Array — HEAP/Quickselect.
  • Task Scheduler — GREEDY/HEAP (idle slots formula or heap).
  • Design Twitter — HEAP + HASH (k‑way merge by timestamps).
  • Find Median From Data Stream — Two Heaps (max‑left/min‑right).
  • Subsets — BTK (cascade).
  • Combination Sum — BTK (unbounded, non‑decreasing start).
  • Combination Sum II — BTK (skip dup at same depth).
  • Permutations — BTK (swap/used[]).
  • Subsets II — BTK (skip dup at same depth).
  • Word Search — BTK (DFS grid + visited).
  • Palindrome Partitioning — BTK (expand check).
  • Letter Combinations of Phone Number — BTK (digit→letters).
  • N Queens — BTK (cols/diag sets).
  • Implement Trie (Prefix Tree) — TRIE.
  • Design Add and Search Words — TRIE + BTK (dot wildcard).
  • Word Search II — TRIE + BTK (prune on prefix).
  • Number of Islands — BFS/DFS (grid flood fill).
  • Max Area of Island — DFS (count).
  • Clone Graph — DFS/BFS + HASH (node map).
  • Walls and Gates — BFS multi‑source.
  • Rotting Oranges — BFS (layers with time).
  • Pacific Atlantic Water Flow — BFS/DFS (reverse flow from oceans).
  • Surrounded Regions — BFS/DFS (protect border‑connected).
  • Course Schedule — TOPO (detect cycle).
  • Course Schedule II — TOPO (return order).
  • Graph Valid Tree — UF or DFS (n nodes, n-1 edges & connected).
  • Number of Connected Components (Undirected) — UF/DFS.
  • Redundant Connection — UF (first union failing).
  • Word Ladder — BFS (generic patterns).
  • Network Delay Time — DIJK (PQ).
  • Reconstruct Itinerary — Hierholzer (lexicographic eulerian path).
  • Min Cost to Connect All Points — MST (Prim with PQ).
  • Swim in Rising Water — BS‑Answer or DIJK/UF.
  • Alien Dictionary — TOPO (graph from first diff).
  • Cheapest Flights Within K Stops — BF‑like / BFS by hops or DP.
  • Climbing Stairs — DP1 (fib).
  • Min Cost Climbing Stairs — DP1 (rolling).
  • House Robber — DP1 (choose/skip).
  • House Robber II — DP1 (two runs: exclude 0 or n-1).
  • Longest Palindromic Substring — Expand Centers / DP2.
  • Palindromic Substrings — Expand Centers.
  • Decode Ways — DP1 (digit rules).
  • Coin Change — DP1 (min coins; inf init).
  • Maximum Product Subarray — DP1 (track max & min).
  • Word Break — DP1 + TRIE(optional) (prefix in dict).
  • Longest Increasing Subsequence — DP1 or Patience (BS O(n log n)).
  • Partition Equal Subset Sum — DP1 (knap 0/1) (bitset optimize).
  • Unique Paths — DP2 (combinatorics or grid DP).
  • Longest Common Subsequence — DP2 (classic).
  • Best Time to Buy/Sell with Cooldown — DP1 (states: hold/sold/rest).
  • Coin Change II — DP2 (order coins outer).
  • Target Sum — DP1 (subset sum transform).
  • Interleaving String — DP2 (i/j → k).
  • Longest Increasing Path in a Matrix — DP2 + DFS memo (DAG heights).
  • Distinct Subsequences — DP2.
  • Edit Distance — DP2.
  • Burst Balloons — DP2 (interval DP).
  • Regular Expression Matching — DP2 (i/j with */. rules).
  • Maximum Subarray — Kadane.
  • Jump Game — GREEDY (farthest reach).
  • Jump Game II — GREEDY BFS‑levels.
  • Gas Station — GREEDY (single pass; total≥0 + start reset).
  • Hand of Straights — GREEDY + HASH (count & iterate).
  • Merge Triplets to Form Target Triplet — GREEDY (keep feasible).
  • Partition Labels — GREEDY (last index map).
  • Valid Parenthesis String — GREEDY (lo/hi balance).
  • Insert Interval — INTV (merge during scan).
  • Merge Intervals — INTV (sort by start, merge).
  • Non Overlapping Intervals — GREEDY (sort by end; count removals).
  • Meeting Rooms — INTV (sort by start; check overlaps).
  • Meeting Rooms II — INTV + HEAP (min‑heap of end times).
  • Minimum Interval to Include Each Query — INTV + HEAP (sweep).
  • Rotate Image — MATH (transpose + reverse).
  • Spiral Matrix — MATH (layer traversal).
  • Set Matrix Zeroes — MATH (first row/col markers).
  • Happy Number — MATH/SET (cycle detect).
  • Plus One — MATH (carry).
  • Pow(x,n) — BS/MATH (fast power).
  • Multiply Strings — MATH (grade‑school).
  • Detect Squares — ARR/HASH (count points by x/y).
  • Single Number — BIT (xor all).
  • Number of 1 Bits — BIT (n &= n-1).
  • Counting Bits — BIT/DP1 (lowest set bit / offset).
  • Reverse Bits — BIT (shift & mask).
  • Missing Number — BIT/MATH (xor or sum diff).
  • Sum of Two Integers — BIT (bitwise add).
  • Reverse Integer — MATH (overflow guard).

📝 Final tips

  • Sort once if it unlocks TP/GREEDY/INTV.
  • Prefer rolling arrays in DP to cut space.
  • For backtracking on arrays with duplicates: sort, then skip same value at the same tree depth.
  • For “k‑th” problems, try heap before full sort.
  • For “search in answer space”, articulate a monotone predicate and binary‑search it.