A revision-focused cheatsheet covering 267 LeetCode problems, grouped by the reusable pattern behind them. Each pattern has one base problem, a blueprint, the invariant that makes it work, and a checklist of related problems with only the differences that matter.
Legend: 🔑 invariant / key observation · ⚠️ pitfalls · ⏱ complexity of the base problem · E / M / H = Easy / Medium / Hard ·
Roadmap¶
| Section | Patterns Covered |
|---|---|
| Arrays and Two Pointers | Converging pointers, sort + converge, reader/writer |
| Sliding Window | Longest valid, shortest valid, fixed window |
| Stacks | Monotonic stack, greedy digit/char stack, simulation |
| Binary Search | Boundary search, search on the answer |
| Linked Lists | Fast/slow, dummy-head rewiring, merge sort |
| Trees | Return-value DFS, path backtracking, BST, level order, tree-as-graph |
| Heaps and Priority Queues | Frequency + heap, k-way merge |
| Backtracking | Choose/skip, permutations, segmentation, buckets, grid undo, constraints |
| Graphs | Traversal, flood fill, BFS variants, bipartite, topo sort, Dijkstra, DSU, bridges |
| Dynamic Programming | Linear, stock state machine, grid, knapsack, LIS, LCS, interval, game, partition, tree |
| SQL | Self-join, anti-join, ranking, conditional aggregation, windows, first-event |
| More patterns | |
| Hashing and Prefix Sums | Complement lookup, prefix sum + hashmap, set-based sequences |
| Intervals | Merge, sort-by-end greedy, sweep line |
| Greedy | Extending frontier, running surplus, slot formulas |
| Top-K and Two Heaps | Size-k heap, median with two heaps |
| Tries | Basic, wildcard DFS, grid + trie |
| Matrix Manipulation | Rotate, zero-marking, spiral |
| Classic Graph Problems | Number of Islands, Word Ladder, Course Schedule mapped to patterns; Clone Graph |
| Linked List Essentials | Reversal, merging, gap pointer, random-pointer copy |
| Data Structure Design | LRU/LFU, random-access set, iterators, rate limiting |
| Monotonic Deque | Sliding window max/min, prefix-sum deque |
| Minimum Spanning Tree | Kruskal, Prim |
| Tree Traversal and Construction | Path sum/diameter, BST checks, serialization |
| Binary Search Variants | Rotated array, 2D matrix, partition search |
| Bit Manipulation | XOR, bit counting |
| Bitmask and Digit DP | Subset DP, TSP-style, digit DP |
| Math and Number Theory | Fast power, sieve, GCD, modular arithmetic |
| String Algorithms | Palindromes, KMP, rolling hash, parsing |
| Advanced Structures and Variants | Fenwick tree, limited-stop shortest path, reservoir sampling |
| Concurrency Basics | Ordering and alternation primitives |
Suggested revision order: Arrays → Sliding Window → Stacks → Binary Search → Linked Lists → Trees → Heaps → Backtracking → Graphs → DP → SQL. Natural progressions: Binary Search → Search on Answer · Basic BFS → Multi-source BFS → State BFS · DFS on trees → Backtracking → Memoized DP · Kahn's topo sort → DP on DAG.
Arrays and Two Pointers¶
Three pointer shapes cover this whole section: pointers that swap/place from both ends, pointers that converge after sorting, and a reader/writer pair moving in one direction.
AR1 Converging Pointers with Placement¶
Recognition: Reverse/swap in place, or merge two "ends" of a sequence whose extremes sit at the ends (e.g. squares of a sorted array).
Core idea: l = 0, r = n-1; decide something about the two ends, act, move inward.
Blueprint:
1. Initialise l, r at the ends.
2. Skip or compare according to the problem's rule.
3. Swap / write the winner, move the corresponding pointer(s).
Base problem: Reverse String · E
🔑 Every position outside
[l, r]is already final.
⚠️ Squares: write results from the back (largest |value| is always at an end).
⏱ Time O(n) · Space O(1)
- Reverse String · E — Base
- Reverse Vowels of a String · E — Each pointer skips non-vowels before swapping
- Squares of a Sorted Array · E — Compare
abs(a[l])vsabs(a[r]), fill output from the end
AR2 Sort Then Converge¶
Recognition: Pairs/triples with a sum or inequality condition; order of elements doesn't matter, only values (so sorting is allowed).
Core idea: After sorting, a comparison of a[l] + a[r] against a threshold indicates which pointer to move, discarding many pairs at once.
Blueprint:
1. Sort.
2. l = 0, r = n-1.
3. If the pair is too small → l++; too big → r--; valid → count/record and move per the problem.
Base problem: Max Number of K-Sum Pairs · M
Sum == k → count, move both; < k → l++; > k → r--.
🔑 If
a[l] + a[r]is too small,a[l]can't pair with anything≤ a[r], so it is safe to drop.
⚠️ A hashmap gives O(n) for this base problem, but the sorted two-pointer idea is what transfers to the others.
⏱ Time O(n log n) · Space O(1)
- Max Number of K-Sum Pairs · M — Base: exact sum
- Boats to Save People · M — Greedy: heaviest always boards; lightest joins only if it fits (
a[l]+a[r] ≤ limit) - Valid Triangle Number · M — Fix the largest side
a[i]; ifa[l]+a[r] > a[i]then all ofl..r-1work → addr-l,r--.O(n²) - Number of Subsequences That Satisfy the Given Sum Condition · M — If
a[l]+a[r] ≤ target,a[l]is the min and any subset of ther-lelements between is allowed → add2^(r-l)(precompute powers, mod1e9+7)
AR3 Reader/Writer Pointers¶
Recognition: In-place filtering of a sorted array with a "keep at most k" rule, or matching one sequence against another by advancing indices.
Core idea: A fast reader scans; a slow writer marks the end of the valid prefix (or the matching position in the second sequence).
Blueprint: Write the first k elements unconditionally → for each later element x, write it only if x != arr[w-k] → w++.
Base problem: Remove Duplicates from Sorted Array II · M
🔑
arr[0..w)always satisfies the rule; comparing witharr[w-2]is enough because the array is sorted.
⏱ Time O(n) · Space O(1)
- Remove Duplicates from Sorted Array II · M — Base (k = 2)
- Long Pressed Name · E — Two sequences: match
name[i]==typed[j]→ both advance; else allowtyped[j]==typed[j-1](extra press); else fail. Finish wheni == len(name)
Sliding Window¶
All problems here maintain a contiguous window [l, r] and a cheap summary of it (count, sum, frequency).
SW1 Longest Valid Window¶
Recognition: "Longest subarray/substring with at most k of something."
Core idea: Grow r always; shrink l only while the window is invalid; record the length after fixing.
Blueprint:
1. Add a[r] to the summary.
2. while invalid: remove a[l]; l++.
3. ans = max(ans, r-l+1).
Base problem: Max Consecutive Ones III · M
Summary = number of zeros in window; invalid when zeros > k.
🔑 Validity is monotone: any sub-window of a valid window is valid, so
lnever needs to move backward.
⏱ Time O(n) · Space O(1)
- Max Consecutive Ones III · M — Count of zeros ≤ k
- Fruit Into Baskets · M — Hashmap of counts; invalid when distinct types > 2 (delete keys at count 0)
SW2 Shortest Valid Window¶
Recognition: "Minimum length subarray with sum/property ≥ target", all values positive.
Core idea: Expand until valid, then shrink as far as possible while still valid, recording the minimum each time.
Base problem: Minimum Size Subarray Sum · M
🔑 Positive numbers make the sum monotone in window size, so the shrink loop is safe.
⚠️ Record the answer inside the shrink loop. With negatives this fails (needs prefix sums + monotonic deque).
⏱ Time O(n) · Space O(1)
- Minimum Size Subarray Sum · M — Base; return 0 if never valid
SW3 Fixed-Size Window with Frequency Match¶
Recognition: Anagram / permutation of a pattern inside a larger string.
Core idea: Window length is fixed to len(p); slide by adding the new right char and removing the char that leaves; compare frequency arrays (or track a matches counter to avoid the 26-compare).
Base problem: Find All Anagrams in a String · M
🔑 Two strings are anagrams iff their count arrays are equal; sliding updates counts in
O(1).
⏱ Time O(n) (26 compares per step) · Space O(1)
- Find All Anagrams in a String · M — Base; collect start indices
Stacks¶
ST1 Monotonic Stack for Next Greater / Span¶
Recognition: "Next/previous greater (or smaller) element", "how many consecutive days ≤ today".
Core idea: Keep a stack of candidates in monotone order; a new element resolves (pops) every candidate it beats.
Blueprint:
1. Stack holds indices with values in decreasing order.
2. For each element, while stack and a[top] < x: res[pop] = x.
3. Push the current index.
Base problem: Next Greater Element II · M
Circular array → loop i over 0..2n-1, use a[i % n], push only when i < n.
🔑 Each element is pushed and popped once → amortised
O(1)per element.
⏱ Time O(n) · Space O(n)
- Next Greater Element II · M — Base (circular)
- Online Stock Span · M — Looks backward and is online: stack of
(price, span); pop whiletop.price ≤ price, accumulating spans
ST2 Greedy Monotonic Stack (Lexicographic)¶
Recognition: "Smallest number/string after removing k digits / duplicates", result must keep original order.
Core idea: Build the answer on a stack; if the incoming char is smaller than the top, popping the top makes the result lexicographically smaller (when allowed).
Base problem: Remove K Digits · M
while k>0 and top > digit: pop, k-- → push → afterwards drop k from the end → strip leading zeros → empty means "0".
🔑 The stack is always non-decreasing (as far as removals allow).
⏱ Time O(n) · Space O(n)
- Remove K Digits · M — Base: budget
k - Remove Duplicate Letters · M — No budget; instead pop
toponly iftop > candtopappears again later (last[top] > i). Skip chars already in stack (inStackset)
ST3 Stack Simulation¶
Recognition: Nested structure or a sequence of events where the most recent item interacts first.
Base problem: Decode String · M
On [ push (currentString, k); on ] pop and repeat; build multi-digit k while reading digits.
🔑 The stack saves the "outer context" while the inner one is processed.
⏱ Time O(output length) · Space O(n)
- Decode String · M — Base: nested contexts
- Asteroid Collision · M — Collide only when
top > 0and new< 0; compareabs, equal → both vanish; keep popping while the new one wins
Binary Search¶
BS1 Boundary Search on Indices¶
Recognition: Sorted data, or any array where a yes/no predicate flips once (
F F F T T T).
Core idea: Find the first index where the predicate is true.
Blueprint: lo, hi → mid → if pred(mid): hi = mid else lo = mid+1 → stop at lo == hi.
Base problem: Find First and Last Position of Element in Sorted Array · M
Run the boundary search twice: first index ≥ target, and first index > target minus 1.
🔑 Compare against
targetwith the predicate, never test equality mid-loop; that is what keeps the two boundaries distinct.
⏱ Time O(log n) · Space O(1)
- Find First and Last Position of Element in Sorted Array · M — Base: two boundaries
- Find Peak Element · M — Array isn't sorted; predicate is
nums[mid] > nums[mid+1]("we are on a descending slope"). A peak always exists on the uphill side
BS2 Binary Search on the Answer¶
Recognition: "Minimise the maximum" / "find the minimum X such that it's possible", with a greedy feasibility check.
Core idea: The answer lies in a numeric range; feasible(x) is monotone (if x works, larger x works); binary-search the smallest feasible x.
Blueprint:
1. Pick bounds: lo = obvious lower bound, hi = always-feasible value.
2. Write feasible(x) greedily in O(n).
3. feasible(mid) → hi = mid, else lo = mid+1.
Base problem: Capacity To Ship Packages Within D Days · M
lo = max(weights), hi = sum(weights); feasible(cap) = pack greedily, count days ≤ D.
🔑 A larger capacity never needs more days, which gives monotonicity.
⚠️ Bounds matter: lo below max(weights) makes the greedy check meaningless.
⏱ Time O(n log(sum)) · Space O(1)
- Capacity To Ship Packages Within D Days · M — Base
- Minimum Number of Days to Make m Bouquets · M — Answer = a day;
feasible(day)counts runs ofkadjacent bloomed flowers ≥m. Return-1upfront ifm*k > n(uselong). Boundsmin..max(bloomDay)
Linked Lists¶
LL1 Fast/Slow and Meeting Pointers¶
Recognition: Cycle, middle node, or intersection, with
O(1)space expected.
Base problem: Linked List Cycle II · M Slow moves 1, fast moves 2. When they meet, reset one pointer to head; advance both by 1 → they meet at the cycle entry.
🔑 Distance from head to entry equals distance from the meeting point to the entry (mod cycle length).
⏱ Time O(n) · Space O(1)
- Linked List Cycle II · M — Base
- Palindrome Linked List · E — Fast/slow finds the middle → reverse the second half → compare (optionally restore)
- Intersection of Two Linked Lists · E — No fast/slow; pointers switch to the other head at the end, so both walk
lenA+lenBand meet at the intersection (or both hitnull)
LL2 Dummy Head and Pointer Rewiring¶
Recognition: The head may change or be deleted; relinking nodes in place.
Core idea: Put a dummy before the head; keep a prev pointer to the last node known to be final; rewire prev.next.
Base problem: Remove Duplicates from Sorted List II · M
If cur.val == cur.next.val, skip every node with that value and set prev.next to the next distinct node; otherwise prev = cur.
🔑
prevonly advances when the next node is confirmed to stay.
⏱ Time O(n) · Space O(1)
- Remove Duplicates from Sorted List II · M — Base
- Swap Nodes in Pairs · M —
prev.next=b; a.next=b.next; b.next=a; prev=aper pair - Odd Even Linked List · M — Two chains (odd/even) built in one pass; finally
odd.next = evenHead
LL3 Merge Sort on a List¶
Recognition: Sort a linked list in
O(n log n).
- Base problem: Sort List · M Find the middle (fast/slow), cut the list, sort each half recursively, merge two sorted lists.
🔑 Lists merge in
O(1)extra space and can't be random-accessed, so merge sort beats quick sort here.
⚠️ Cut the list (mid.next = null) before recursing. Bottom-up merging gives O(1) space.
⏱ Time O(n log n) · Space O(log n) recursion
Trees¶
TR1 Return-Value DFS¶
Recognition: The answer at a node is combined from answers of its children.
- Base problem: Lowest Common Ancestor of a Binary Tree · M
Return the node if
rootis null/p/q. Recurse left and right. If both return non-null,rootis the LCA; otherwise return whichever is non-null.
🔑 A non-null return means "p or q (or their LCA) lives below me".
⏱ Time O(n) · Space O(h)
TR2 Root-to-Leaf Path DFS with Backtracking¶
- Base problem: Path Sum II · M
Append the node, subtract from the target; at a leaf with remaining
== 0, copy the path; recurse; pop on return.
🔑 One shared path list + undo on exit = no per-call copies.
⚠️ Copy at the leaf, otherwise every result aliases the same list.
⏱ Time O(n²) worst (copying paths) · Space O(h) besides output
TR3 BST Navigation and Deletion¶
- Base problem: Delete Node in a BST · M Go left/right by comparison. On match: 0 or 1 child → return the other child; 2 children → replace with the in-order successor (min of right subtree) and delete that successor from the right subtree.
🔑 In-order successor keeps the BST ordering; recursion returns the new subtree root so parents relink automatically.
⏱ Time O(h) · Space O(h)
TR4 In-Place Restructuring¶
- Base problem: Flatten Binary Tree to Linked List · M
For each node with a left child: find the rightmost node of the left subtree, attach
node.rightthere, movelefttoright, null the left, step right.
🔑 The rightmost node of the left subtree is the pre-order predecessor of
node.right.
⏱ Time O(n) · Space O(1)
TR5 Level-Order BFS¶
Recognition: Answers are organised by depth, or neighbours "in the same level".
Core idea: Process the queue one level at a time (size = len(queue)), and adapt the work done inside each level.
Base problem: Binary Tree Zigzag Level Order Traversal · M
Standard level order with a direction flag; reverse (or appendleft) on alternate levels.
⏱ Time O(n) · Space O(w) (max width)
- Binary Tree Zigzag Level Order Traversal · M — Base
- Populating Next Right Pointers in Each Node · M — Perfect tree: link
left.next = rightandright.next = node.next.left, using the already-builtnextof the level above →O(1)space - Vertical Order Traversal of a Binary Tree · H — Tag nodes
(col, row, val)via BFS/DFS; sort by col, then row, then value (ties at the same cell sort by value).O(n log n)
TR6 Tree as Graph (Parent Map + BFS)¶
Recognition: Distances from a node in all directions, including upward.
- Base problem: All Nodes Distance K in Binary Tree · M
DFS to record
parent[node]; BFS fromtargetover{left, right, parent}with a visited set; collect nodes at levelK.
🔑 Adding parent edges turns the tree into an undirected graph, so ordinary BFS gives distances.
⏱ Time O(n) · Space O(n)
TR7 Exploit Complete-Tree Structure¶
- Base problem: Count Complete Tree Nodes · E
Compute leftmost depth and rightmost depth. Equal → perfect tree,
2^h - 1. Otherwise1 + count(left) + count(right).
🔑 In a complete tree at least one child subtree is perfect, so only one side recurses deeply.
⏱ Time O(log² n) · Space O(log n)
Heaps and Priority Queues¶
HP1 Frequency Count + Heap¶
Recognition: "Top k frequent", "order by frequency", "rearrange so equal items aren't adjacent".
Core idea: Count frequencies, then use a heap (or bucket sort) keyed by count.
Base problem: Top K Frequent Words · M
Heap keyed by (-count, word) so ties break alphabetically; pop k.
⚠️ Tie-breaking order must be encoded in the key (or comparator).
⏱ Time O(n log k) with a size-k heap, O(n log n) with a full heap · Space O(n)
- Top K Frequent Words · M — Base
- Sort Characters By Frequency · M — Output all chars grouped by count desc; bucket by frequency gives
O(n) - Reorganize String · M — Greedy: max-heap; repeatedly take the two most frequent distinct chars (or hold the previous char out one round). Impossible if
max count > (n+1)/2
HP2 K-Way Merge / Kth Smallest¶
- Base problem: Kth Smallest Element in a Sorted Matrix · M
Treat each row as a sorted list. Push
(value, r, c)for each row's first element in a min-heap; popktimes, pushing the right neighbour each time.
🔑 The heap always holds the smallest unseen element of each list.
💡 Alternative: binary search on value (BS2) with an O(n) staircase count of elements ≤ mid.
⏱ Time O(min(n,k) + k log n) · Space O(n)
Backtracking¶
All patterns share the template: choose → recurse → undo. They differ in what a choice is and how duplicates and dead ends are avoided.
BT1 Choose/Skip (Index-Driven)¶
Recognition: Subsets, combinations, or per-element binary decisions.
Base problem: Combinations · M
dfs(start, path): if len == k record; for i in start..n: add i, dfs(i+1), pop. Prune with i ≤ n-(k-len)+1.
🔑 The
startindex enforces increasing order, which prevents duplicate combinations.
⏱ Time O(C(n,k)·k) · Space O(k)
- Combinations · M — Base
- Combination Sum III · M — Numbers 1–9, exactly
kof them, sumn; prune when the sum exceedsn - Letter Case Permutation · M — Binary decision per character (letters: lower/upper; digits: one option); no start-index loop
- Maximum Length of a Concatenated String with Unique Characters · M — Include/skip each string; keep a bitmask of used letters, skip a string that overlaps or has internal duplicates
BT2 Permutations (Used Set)¶
Base problem: Permutations II · M
Sort; used[]; at each depth try every unused element; skip nums[i] == nums[i-1] when !used[i-1].
🔑 Among equal values, enforce that they're used left-to-right, so each distinct permutation appears once.
⏱ Time O(n · n!) · Space O(n)
- Permutations II · M — Base: dedupe
- Beautiful Arrangement · M — Fill positions
1..n; numberiallowed atposonly ifi % pos == 0 or pos % i == 0. Counts instead of listing; pruning does the work
BT3 String Segmentation and Expression Building¶
Recognition: Cut a string into pieces or insert operators between digits; each step picks the next piece length.
Base problem: Restore IP Addresses · M
dfs(idx, parts): try segment lengths 1–3, require value 0..255 and no leading zero; succeed when parts == 4 and idx == len(s).
⏱ Time bounded by 3^4 splits · Space O(1)
- Restore IP Addresses · M — Base: fixed number of parts
- Word Break II · H — Try each dictionary-word prefix; memoise
dfs(start)→ list of sentences (otherwise exponential blow-up) - Expression Add Operators · H — Choose the next number slice and operator; track
valueandlastoperand so*is applied asvalue - last + last*cur. Skip numbers with leading zeros; uselong
BT4 Bucket Partitioning¶
Recognition: Split items into
kgroups of equal sum.
Base problem: Partition to K Equal Sum Subsets · M
target = sum/k. Place each number (sorted descending) into a bucket that still fits.
🔑 Prune: if two buckets have the same current sum, trying the second one is redundant; if any item
> target, fail immediately.
💡 Bitmask DP alternative: dp[mask] = leftover in the current bucket.
⏱ Time O(k · 2^n) with memo, worst naive O(k^n) · Space O(n)
- Partition to K Equal Sum Subsets · M — Base: general
k - Matchsticks to Square · M — Same with
k = 4(side = perimeter/4)
BT5 Grid Path with Visit-Undo¶
- Base problem: Path with Maximum Gold · M Start DFS from every non-zero cell. Mark the cell visited (set to 0), explore 4 directions, take the best, restore the cell.
🔑 Restoring on exit lets other paths reuse the cell.
⏱ Time ≈ O(g · 3^g) (g ≤ 25 gold cells) · Space O(g)
BT6 Constraint Satisfaction¶
- Base problem: Sudoku Solver · H
Keep row/column/box bitmasks. Pick an empty cell (optionally the one with fewest candidates), try digits, recurse, undo; return
trueearly on success.
🔑 Fail fast: constraint masks make invalid placements
O(1)to reject.
⏱ Exponential worst case, heavily pruned in practice · Space O(1) extra
Graphs¶
Common ingredients: adjacency list, visited, queue/stack. The patterns differ in the kind of question (reachability, distance, ordering, connectivity) and in what a node is (a vertex, a grid cell, or an abstract state).
GR1 Connectivity and Reachability¶
Recognition: "Is there a path?", "how many components?", "can everything be reached?"; edges given or derivable.
Core idea: Build adjacency, traverse from a start with a visited set, read the answer from what was visited.
Base problem: Find if Path Exists in Graph · E
🔑 Mark visited on enqueue/entry, not on pop, to avoid revisits.
⏱ Time O(V+E) · Space O(V+E)
- Find if Path Exists in Graph · E — Base
- Number of Provinces · M — Count components on an adjacency matrix (DSU also works)
- Keys and Rooms · M — Directed; reachable from room 0 must cover all rooms
- Evaluate Division · M — Edges carry weights
a/band reverseb/a; DFS/BFS multiplies weights along the path; unknown variable →-1 - Detonate the Maximum Bombs · M — Edges are implicit:
i → jifdist² ≤ r_i²(directed, use integers); DFS from every bomb, take the max reach.O(n³)
GR2 Grid Flood Fill and Islands¶
Recognition: Regions of connected land cells, with a condition about borders or another grid.
Base problem: Number of Enclaves · M Flood-fill from every border land cell (mark visited/sink), then count the remaining land cells.
🔑 Anything reachable from the border is not enclosed, so eliminate those first and what's left is the answer.
⏱ Time O(mn) · Space O(mn) recursion worst case
- Number of Enclaves · M — Base: count remaining cells
- Number of Closed Islands · M — Sink border-connected land first, then count components of what remains
- Count Sub Islands · M — Island in
grid2counts only if every cell is land ingrid1; flag a failure while flooding (or sinkgrid2cells wheregrid1 == 0first) - Making A Large Island · H — Label each component with an id and size; for each
0, sum sizes of distinct neighbouring ids+1; if there are no zeros the answer isn²
GR3 BFS Shortest Path (Unweighted)¶
- Base problem: Shortest Path in Binary Matrix · M
BFS from
(0,0)over 8 directions; distance = number of BFS levels;-1if start or end is blocked.
🔑 In an unweighted graph the first time BFS reaches a node is the shortest distance.
⏱ Time O(mn) · Space O(mn)
GR4 Multi-Source BFS¶
Recognition: "Distance to the nearest X" for every cell, or expand from a whole region.
Core idea: Put all sources in the queue with distance 0, then run BFS once.
Base problem: 01 Matrix · M
Enqueue every 0 with distance 0; neighbours that are 1 get dist+1.
🔑 One BFS from a virtual super-source replaces one BFS per cell.
⏱ Time O(mn) · Space O(mn)
- 01 Matrix · M — Base
- Shortest Bridge · M — Two phases: DFS to find one island and enqueue all its cells; then multi-source BFS until reaching the other island. Answer = number of
0s crossed
GR5 BFS on an Implicit State Graph¶
Recognition: "Minimum number of moves/steps" where nodes are configurations; neighbours are generated rather than read from an edge list.
Core idea: Define the state, the neighbour function, the start, and the goal. BFS gives the minimum number of moves.
Base problem: Open the Lock · M
State = 4-digit string. Neighbours = turn any wheel ±1 (wrap 9↔0): 8 neighbours. Dead ends are pre-marked visited; if "0000" is a dead end, return -1.
⏱ Time O(10⁴ · 8) · Space O(10⁴)
- Open the Lock · M — Base
- Minimum Genetic Mutation · M — Neighbour = change one char to
A/C/G/Tand the result must be in the bank - Snakes and Ladders · M — State = square number; map to
(row, col)with the zig-zag layout; neighbours+1..+6, then follow a snake/ladder if present - Shortest Path Visiting All Nodes · H — State =
(node, visitedMask); start from every(i, 1<<i); goalmask == full. Nodes may be revisited with a different mask.O(n²·2ⁿ)
GR6 DFS Path Enumeration in a DAG¶
- Base problem: All Paths From Source to Target · M
DFS from
0carrying the current path; record it when it reachesn-1.
🔑 Because the graph is a DAG, no
visitedset is needed, and adding one would incorrectly cut valid paths.
⏱ Time O(2ⁿ · n) worst case · Space O(n) besides output
GR7 Bipartite Coloring¶
Recognition: "Split into two groups with no conflicts inside a group", "odd cycle".
Base problem: Is Graph Bipartite? · M Colour a node, give neighbours the opposite colour (BFS/DFS); a neighbour with the same colour means failure. Start from every uncoloured node (graph may be disconnected).
🔑 A graph is bipartite iff it has no odd cycle.
⏱ Time O(V+E) · Space O(V)
- Is Graph Bipartite? · M — Base
- Possible Bipartition · M — Build the graph from "dislike" pairs first, then the same check
GR8 Topological Sort (Kahn)¶
Recognition: Dependencies/prerequisites; "can everything be built/finished?"; cycle detection in directed graphs; peeling layer by layer.
Core idea: Repeatedly process nodes whose remaining in-degree is 0. Nodes never processed are in (or behind) a cycle.
Base problem: Find All Possible Recipes from Given Supplies · M
Edge ingredient → recipe; indegree[recipe] = #ingredients. Start the queue with supplies; when an item is processed, decrement the in-degree of dependent recipes and enqueue those reaching 0.
🔑 In-degree 0 means "all prerequisites satisfied".
⏱ Time O(V+E) · Space O(V+E)
- Find All Possible Recipes from Given Supplies · M — Base
- Find Eventual Safe States · M — Reverse the edges and peel from terminal nodes (out-degree 0); safe = nodes that get processed. (DFS with 3-colour cycle detection is equivalent)
- Minimum Height Trees · M — Undirected: peel leaves (degree 1) layer by layer until ≤ 2 nodes remain; those are the centres
- Course Schedule IV · M — Process in topological order propagating prerequisite sets (
pre[v] = pre[v] ∪ pre[u] ∪ {u}); withn ≤ 100, Floyd–Warshall closure also works
GR9 Dijkstra and Its Variants¶
Recognition: Shortest/optimal path with non-negative weights, or a path cost that isn't a plain sum (max edge, product).
Core idea: Min-heap on the best known cost; pop the best node; relax neighbours with the problem's own cost-combine rule.
Base problem: Path with Maximum Probability · M
Max-heap on probability; relax p' = p · edgeProb; first pop of the target is optimal.
🔑 Works whenever extending a path never improves it (probabilities ≤ 1, non-negative costs, max of edges).
⏱ Time O(E log V) · Space O(V+E)
- Path with Maximum Probability · M — Base: maximise a product
- Path With Minimum Effort · M — Minimax: cost of a path = max — height difference — ; relax with
max(cur, diff)and keep the min. (Binary search + BFS also works) - Minimum Cost to Make at Least One Valid Path in a Grid · H — Edge cost is 0 if the arrow is followed, 1 if it is changed → 0-1 BFS with a deque (0 → front, 1 → back),
O(mn)
GR10 All-Pairs Shortest Path (Floyd–Warshall)¶
- Base problem: Find the City With the Smallest Number of Neighbors at a Threshold Distance · M
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])forkoutermost; count cities within threshold for eachi; pick the smallest count, tie → largest index.
🔑
kis the loop-outer "allowed intermediate vertices" dimension.
⏱ Time O(n³) · Space O(n²) (fine for n ≤ 100)
GR11 Union-Find¶
Recognition: Merging groups, "are these connected?", counting components, detecting redundant edges.
Core idea: find with path compression, union by size/rank; the answer comes from component structure.
Base problem: Satisfiability of Equality Equations · M
First union all == pairs; then for every != pair, fail if both share a root.
🔑 Order matters: apply all equalities before checking any inequality.
⏱ Time O(n α(n)) · Space O(1) for 26 letters
- Satisfiability of Equality Equations · M — Base
- Number of Operations to Make Network Connected · M — If
edges < n-1→-1; else answer =components - 1 - Accounts Merge · M — Union accounts that share an email (map email → first account); group emails by root; sort each group
- Most Stones Removed with Same Row or Column · M — Union row with column (offset columns); answer =
stones - components - Redundant Connection II · H — Directed: if a node has two parents, test removing the later candidate edge for a cycle; if no node has two parents, return the edge that closes a cycle
GR12 Bridges (Tarjan Low-Link)¶
- Base problem: Critical Connections in a Network · H
DFS records
disc[u]andlow[u](earliest discovery reachable via the subtree plus one back edge). Skip the edge to the parent. Edge(u,v)is a bridge ifflow[v] > disc[u].
🔑 If
v's subtree can't reachuor above without this edge, removing it disconnects the graph.
⚠️ Depth can reach 10⁵; consider an iterative DFS.
⏱ Time O(V+E) · Space O(V+E)
Dynamic Programming¶
Every DP pattern below answers four questions: what does the state mean, what is the transition, what are the base cases, and in what order it is filled. Related problems usually differ only in one of these.
D1 Take/Skip with Lookback¶
Recognition: Each item/day is either taken (blocking neighbours or covering a window) or skipped.
State: dp[i] = best result considering the first i items/days.
Transition: dp[i] = max(dp[i-1], dp[i-2] + gain[i]) (house robber shape).
Base problem: Delete and Earn · M
Bucket by value: gain[v] = v · count(v). Taking v forbids v-1 and v+1, which is exactly house robber over values.
🔑 Reduce the problem to "pick non-adjacent items" by re-indexing.
⏱ Time O(n + maxVal) · Space O(maxVal) (O(1) with rolling)
- Delete and Earn · M — Base
- Minimum Cost For Tickets · M —
dp[d]= min cost through dayd; if not a travel daydp[d] = dp[d-1], else min ofdp[d-1]+c1,dp[d-7]+c7,dp[d-30]+c30(lookback instead of -2)
D2 Min/Max over Splits (Coin-Change Style)¶
State: dp[n] = best answer for value n. Transition: try every first part j and combine with the remainder.
Base problem: Perfect Squares · M
dp[0]=0; dp[n] = 1 + min(dp[n - k²]) for all k² ≤ n. Fill increasing.
⏱ Time O(n√n) · Space O(n)
- Perfect Squares · M — Base: minimise count
- Integer Break · M — Maximise product:
dp[n] = max(j·(n-j), j·dp[n-j])(either keep a part whole or split further)
D3 Counting by Step and State¶
Recognition: "How many ways" after
tsteps; the next step depends on a small current state.
State: dp[step][state]. Transition: sum over allowed previous states. Roll the step dimension.
Base problem: Knight Dialer · M
dp[s][digit] = number of sequences of length s ending at digit; transition via the knight-move table; mod 1e9+7.
⏱ Time O(n · 10 · moves) · Space O(10)
- Knight Dialer · M — Base
- Number of Dice Rolls With Target Sum · M — State =
(dice used, sum); adddp[d-1][s-face]over faces - Domino and Tromino Tiling · M — State = shape of the boundary; collapses to
f(n) = 2·f(n-1) + f(n-3)
D4 Subarray DP Ending at i (Kadane-Style)¶
State: dp[i] = best subarray ending exactly at i. Transition: extend the previous one or restart.
Base problem: Maximum Sum Circular Subarray · M
Answer = max(maxKadane, total - minKadane); if all numbers are negative (maxKadane < 0), return maxKadane.
🔑 A wrapping subarray is the total minus a non-wrapping minimum subarray in the middle.
⏱ Time O(n) · Space O(1)
- Maximum Sum Circular Subarray · M — Base
- Arithmetic Slices · M —
dp[i] = dp[i-1] + 1ifa[i]-a[i-1] == a[i-1]-a[i-2], else 0; answer = sum of alldp[i]
D5 Multi-Pointer Generation¶
- Base problem: Ugly Number II · M
ugly[0]=1; pointersp2, p3, p5; next = min ofugly[p2]·2,ugly[p3]·3,ugly[p5]·5; advance every pointer that produced the min (handles duplicates).
⏱ Time O(n) · Space O(n)
D6 Stock State Machine¶
Recognition: Buy/sell with constraints (fee, transaction limit); each day is in a state (holding or not, transactions used).
State: hold, sold (or dp[j][0/1] for j transactions). Transition: move between states, paying fees or incrementing the transaction count when you buy.
Base problem: Best Time to Buy and Sell Stock II · M
hold = max(hold, sold - p), sold = max(sold, hold + p) (equivalently, sum every positive daily difference).
⏱ Time O(n) · Space O(1)
- Best Time to Buy and Sell Stock II · M — Base: unlimited transactions
- Best Time to Buy and Sell Stock with Transaction Fee · M — Subtract the fee when selling (or buying)
- Best Time to Buy and Sell Stock III · H — At most 2 transactions: four states
buy1, sell1, buy2, sell2 - Best Time to Buy and Sell Stock IV · H — General
k:buy[j], sell[j]arrays; ifk ≥ n/2, it degenerates to Stock II.O(nk)
D7 Grid Path DP¶
State: dp[i][j] = best/count to reach (i,j). Transition: from top and/or left. Order: row-major. Base: first row/col.
Base problem: Minimum Path Sum · M
dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
⏱ Time O(mn) · Space O(n) with a rolling row
- Minimum Path Sum · M — Base
- Unique Paths II · M — Count paths; obstacle cell →
dp = 0 - Triangle · M — Parents are
(i-1, j-1)and(i-1, j); or go bottom-up in place - Minimum Falling Path Sum · M — Three parents in the previous row:
j-1, j, j+1(bounds check) - Dungeon Game · H — Backward DP from the bottom-right:
need[i][j] = max(1, min(need[i+1][j], need[i][j+1]) - cell). Forward DP fails because the future decides how much HP is needed now
D8 Square Submatrix DP¶
State: dp[i][j] = side of the largest all-ones square whose bottom-right corner is (i,j).
Transition: if cell is 1: 1 + min(top, left, top-left), else 0.
Base problem: Maximal Square · M
Answer = max(dp)².
- Maximal Square · M — Base: answer = max side²
- Count Square Submatrices with All Ones · M —
dp[i][j]also equals the number of squares ending at that corner → answer = sum of alldp
⏱ Time O(mn) · Space O(n)
D9 Layered Multi-Dimensional State¶
Recognition: A time/step dimension plus positions; the state is bigger than one cell.
Base problem: Cherry Pickup II · H
Two robots move down the same rows simultaneously: dp[r][c1][c2] = best total at row r. Each of 9 move combinations; add cherries once if c1 == c2.
🔑 Processing both robots in lock-step by row makes their order irrelevant.
⏱ Time O(R · C² · 9) · Space O(C²) rolling
- Cherry Pickup II · H — Base
- Out of Boundary Paths · M —
dp[moves][r][c]counts paths; going off-grid adds 1 to the count; mod1e9+7
D10 0/1 Knapsack / Subset Sum¶
Recognition: Each item used at most once; a capacity (or two) constrains choices.
State: dp[cap] = reachable / best value at capacity cap. Transition: dp[c] = max(dp[c], dp[c-w] + v). Order: iterate capacity backward to avoid reusing an item.
Base problem: Last Stone Weight II · M
Split the stones into two groups with the smallest difference → find the achievable subset sum closest to total/2.
🔑 Smashing stones is equivalent to assigning each stone a
+or-sign.
⏱ Time O(n · total/2) · Space O(total/2)
- Last Stone Weight II · M — Base: boolean subset sum
- Ones and Zeroes · M — Two capacities (zeros, ones):
dp[m][n], both dimensions backward; maximise count - Profitable Schemes · H — Count schemes:
dp[members][profit]with profit capped atminProfit; mod1e9+7
D11 Unbounded Knapsack (Counting Orderings)¶
- Base problem: Combination Sum IV · M
dp[t] = Σ dp[t - num],dp[0] = 1. The target is the outer loop and the items the inner loop, so different orders count as different sequences.
🔑 Loop order decides combinations vs permutations: items outer = combinations; target outer = permutations.
⏱ Time O(target · n) · Space O(target)
D12 LIS-Style Chain DP¶
Recognition: Longest chain where each element can follow a previous one under a pairwise rule.
State: dp[i] = longest chain ending at i. Transition: max(dp[j] + 1) over j < i that can precede i. Sort first if the order isn't given.
Base problem: Largest Divisible Subset · M
Sort; dp[i] = 1 + max dp[j] where a[i] % a[j] == 0; keep prev[i] to rebuild the subset.
🔑 In a sorted array, divisibility is transitive, so checking against the chain's last element suffices.
⏱ Time O(n²) · Space O(n)
- Largest Divisible Subset · M — Base: reconstruct the chain
- Longest String Chain · M — Sort by length; for each word try deleting each char and look up that predecessor in a hashmap
- Number of Longest Increasing Subsequence · M — Track
len[i]andcnt[i]; when a longer chain is found, reset the count; when equal, add - Longest Arithmetic Subsequence · M — State gains a dimension:
dp[i][diff]= length ending atiwith common differencediff(hashmap per index) - Maximum Length of Pair Chain · M — Same DP after sorting, but greedy is better: sort by end and take whenever
start > lastEnd(O(n log n))
D13 LIS via Sort + Binary Search¶
- Base problem: Russian Doll Envelopes · H
Sort by width ascending, and for equal widths by height descending; then find the LIS of heights using the
tailsarray with binary search.
🔑 Descending heights on ties prevent two envelopes with the same width from chaining.
⏱ Time O(n log n) · Space O(n)
D14 LCS Family¶
Recognition: Two strings/arrays, the answer relates to what they have in common.
State: dp[i][j] = answer for prefixes a[:i], b[:j].
Transition: a[i-1]==b[j-1] → dp[i-1][j-1]+1; else max(dp[i-1][j], dp[i][j-1]).
Base: row/column 0 = 0. Order: row-major.
Base problem: Uncrossed Lines · M (it is LCS on two arrays)
⏱ Time O(mn) · Space O(min(m,n)) with rolling (full table needed for reconstruction)
- Uncrossed Lines · M — Base
- Delete Operation for Two Strings · M — Answer =
m + n - 2·LCS - Minimum ASCII Delete Sum for Two Strings · M — Weighted version: minimise the ASCII sum of deleted chars (or
total - 2·maxCommonAsciiSum) - Shortest Common Supersequence · H — Build the LCS table, then reconstruct by walking back: emit matching chars once, and the non-matching ones from whichever side the step comes from
- Maximum Length of Repeated Subarray · M — Contiguous version: on mismatch
dp = 0(reset), answer =max(dp)
D15 Palindromic Subsequence (Interval)¶
State: dp[i][j] = answer for substring s[i..j]. Transition: s[i]==s[j] → 2 + dp[i+1][j-1]; else max(dp[i+1][j], dp[i][j-1]). Order: by increasing length (or i descending).
Base problem: Longest Palindromic Subsequence · M
(equivalently LCS(s, reverse(s))).
⏱ Time O(n²) · Space O(n²)
- Longest Palindromic Subsequence · M — Base
- Minimum Insertion Steps to Make a String Palindrome · H — Answer =
n - LPS(characters outside the LPS need a mirror)
D16 Palindrome Partition and Pattern Matching¶
Two distinct string DPs that don't fit the families above.
- Palindrome Partitioning II · H — Precompute
isPal[i][j](O(n²)), thencuts[i] = min(cuts[j-1] + 1)overjwithisPal[j][i];cuts[i]=0if the whole prefix is a palindrome. (This is also D19 on top of a palindrome table) - Wildcard Matching · H —
dp[i][j]=s[:i]matchesp[:j].?or equal char →dp[i-1][j-1];*→dp[i][j-1](empty) ordp[i-1][j](consume one more char). Base:dp[0][0]=true; leading*s match empty.O(mn)
D17 Interval DP (Split Point)¶
Recognition: The answer for a range
[l, r]is built by choosing a split/last/first elementkinside it.
State: dp[l][r]. Transition: min/max/sum over k of dp[l][k] + dp[k][r] + cost. Order: by increasing interval length.
Base problem: Minimum Cost to Cut a Stick · H
Sort cuts, add 0 and n as endpoints; dp[i][j] = min over k in (i,j) (dp[i][k] + dp[k][j]) + (cuts[j] - cuts[i]).
🔑 Think of
kas the last operation on the range; the two sides then become independent.
⏱ Time O(n³) · Space O(n²)
- Minimum Cost to Cut a Stick · H — Base
- Minimum Score Triangulation of Polygon · M —
k= third vertex of the triangle on edge(i,j); costv[i]·v[k]·v[j] - Guess Number Higher or Lower II · M —
k= first guess;k + max(dp[l][k-1], dp[k+1][r])minimised (worst-case minimax) - Strange Printer · H —
dp[i][j] = dp[i+1][j] + 1, or merge with anykwheres[k]==s[i]:dp[i+1][k-1] + dp[k][j] - Unique Binary Search Trees · M —
k= root;dp[n] = Σ dp[k-1]·dp[n-k](Catalan numbers,O(n²))
D18 Game DP (Minimax)¶
Recognition: Two players alternate with optimal play; answer is "can first player win" or a score difference.
Core idea: Define dp[state] = best score difference (current player minus opponent) from that state; the opponent's turn becomes a subtraction.
Base problem: Predict the Winner · M
dp[i][j] = max(a[i] - dp[i+1][j], a[j] - dp[i][j-1]); first player wins iff dp[0][n-1] ≥ 0.
⏱ Time O(n²) · Space O(n) rolling
- Predict the Winner · M — Base: pick from either end
- Stone Game II · M — State
(i, M)= suffix start and current limit; takeX ≤ 2Mpiles; use suffix sums:best = suffix[i] - min over X dp(i+X, max(M,X)) - Can I Win · M — State = bitmask of used numbers (the remaining total is derived from the mask); memoise win/lose; handle
desiredTotal ≤ 0andsum(1..max) < desiredupfront
D19 Partition DP (Last Segment)¶
Recognition: Split an array into consecutive segments, each with a cost/score determined by its contents.
State: dp[i] = best answer for the first i items. Transition: choose the length of the last segment: dp[i] = best over j (dp[j] + cost(j+1..i)).
Base problem: Partition Array for Maximum Sum · M
Segments of length ≤ k; value of a segment = max · length. Keep a running max while extending the segment backward.
⏱ Time O(nk) · Space O(n)
- Partition Array for Maximum Sum · M — Base
- Filling Bookcase Shelves · M — Segment = shelf; width must fit; shelf height = max height; minimise total height
- Minimum Difficulty of a Job Schedule · H — Extra dimension: exactly
ddays →dp[day][i]; day cost = max in segment. Return-1ifn < d
D20 Tree DP¶
State: values returned by the post-order DFS at each node, describing the subtree in a few states.
Base problem: House Robber III · M
Return a pair (rob, skip) per node: rob = val + left.skip + right.skip; skip = max(left) + max(right).
⏱ Time O(n) · Space O(h)
- House Robber III · M — Base: 2 states
- Binary Tree Cameras · H — 3 states: has camera / covered without camera / not covered. Greedy equivalent: put a camera on the parent of an uncovered node; treat
nullas covered
SQL¶
These aren't algorithms with complexity, but the same logic applies: recognise the shape, then reuse the template.
SQ1 Self-Join for Row Relationships¶
Recognition: Compare a row with another row of the same table (manager, previous day, duplicate).
Base problem: Employees Earning More Than Their Managers · E
FROM Employee e JOIN Employee m ON e.managerId = m.id WHERE e.salary > m.salary.
- Employees Earning More Than Their Managers · E — Base
- Rising Temperature · E — Join on dates one day apart (
DATEDIFF = 1, orLAG) - Delete Duplicate Emails · E —
DELETEwith a self-join keeping the smallerid
SQ2 Anti-Join (Absence)¶
- Base problem: Customers Who Never Order · E
LEFT JOIN Orders ... WHERE Orders.id IS NULL(orNOT EXISTS). ⚠️NOT INbreaks if the subquery returnsNULL.
SQ3 Group-Level Filtering¶
Recognition: Keep rows/groups depending on an aggregate property.
Base problem: Duplicate Emails · E
GROUP BY email HAVING COUNT(*) > 1.
- Duplicate Emails · E — Base
- Managers with at Least 5 Direct Reports · M — Group by
managerId,HAVING COUNT ≥ 5, then join back to get the name - Investments in 2016 · M — Row-level result depends on two group counts:
COUNT(*) OVER (PARTITION BY tiv_2015) > 1andCOUNT(*) OVER (PARTITION BY lat, lon) = 1
SQ4 Ranking and Top-N per Group¶
Recognition: "Nth highest", "top 3 per department", "rank with ties".
Base problem: Department Highest Salary · M
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) in a subquery; filter rank = 1.
🔑 Use
DENSE_RANKwhen ties should share a rank without leaving gaps.
- Department Highest Salary · M — Base
- Department Top Three Salaries · H — Filter
rank ≤ 3(ties count once) - Rank Scores · M —
DENSE_RANK()with no partition - Second Highest Salary · M — Must return
NULLif absent → wrap in a subquery/MAXorIFNULL - Nth Highest Salary · M — Function with a parameter:
DENSE_RANKorDISTINCT ... LIMIT 1 OFFSET N-1; computeN-1outside theLIMITin MySQL
SQ5 Conditional Aggregation and CASE Labelling¶
Base problem: Capital Gain/Loss · M
SUM(CASE WHEN operation='Buy' THEN -price ELSE price END) grouped by stock.
- Capital Gain/Loss · M — Base
- Count Salary Categories · M — Categories with zero rows must still appear →
UNION ALLof three counts (or a category table +LEFT JOIN) - Tree Node · M —
CASE:p_id IS NULL→ Root;id IN (SELECT p_id ...)→ Inner; else Leaf - Trips and Users · H — Filter trips whose client and driver are both unbanned; cancellation rate =
AVG(status != 'completed')(orSUM(CASE)/COUNT) per day; round to 2 decimals
SQ6 Running Totals and Sequences (Window Functions)¶
Base problem: Last Person to Fit in the Bus · M
SUM(weight) OVER (ORDER BY turn) as running total; keep rows ≤ 1000; take the last by turn.
- Last Person to Fit in the Bus · M — Base
- Restaurant Growth · M — Sliding 7-day window: aggregate per day first, then
SUM(...) OVER (ORDER BY day ROWS 6 PRECEDING); drop the first 6 rows - Consecutive Numbers · M — Three equal values in consecutive ids:
LAG/LEAD, or three self-joins onid,id+1,id+2
SQ7 First Event / Latest Before a Date¶
Recognition: Per entity, the earliest (or latest-as-of) record, then something related to it.
Base problem: Product Sales Analysis III · M
Per product find MIN(year), then join (or IN) back to get that year's quantity and price.
- Product Sales Analysis III · M — Base
- Immediate Food Delivery II · M — First order per customer (
MIN(order_date)), then % whereorder_date = customer_pref_delivery_date - Game Play Analysis IV · M — First login per player, then check a login exactly the next day; fraction of players
- Product Price at a Given Date · M — Latest change
≤ cutoffper product; products with no change by then default to price10(UNIONorLEFT JOINwithCOALESCE)
SQ8 UNION-Based Reshaping¶
Base problem: Friend Requests II: Who Has the Most Friends · M
Stack requester_id and accepter_id with UNION ALL so each friendship counts for both sides; GROUP BY id, ORDER BY COUNT DESC LIMIT 1.
- Friend Requests II: Who Has the Most Friends · M — Base
- Movie Rating · M — Two independent "top 1" queries (most ratings by user; best average rating in Feb 2020 per movie), each with deterministic lexicographic tie-breaks, combined with
UNION ALL
More Patterns for Revision¶
The sections below cover additional patterns that recur frequently across practice sets. (P) marks LeetCode Premium problems.
Hashing and Prefix Sums¶
HS1 Complement Lookup¶
Recognition: "Find two items with a relationship", or "group items that are equivalent".
Core idea: Store what has been seen in a map; for each new item, look up what it needs (or its canonical key).
Base problem: Two Sum · E
For each x, check target - x in the map, then insert x (so an element isn't paired with itself).
⏱ Time O(n) · Space O(n)
- Two Sum · E — Base
- Group Anagrams · M — Canonical key = sorted string or a 26-count tuple; group by key
HS2 Prefix Sum with Hashmap¶
Recognition: "Number/length of subarrays with sum (or property) equal to / divisible by k", especially with negative numbers (sliding window fails).
Core idea: Subarray (i, j] has sum k iff prefix[j] - prefix[i] = k. Track how many times each prefix value has occurred.
Blueprint:
1. count = {0: 1}, prefix = 0.
2. For each x: prefix += x; ans += count[prefix - k]; count[prefix] += 1.
Base problem: Subarray Sum Equals K · M
🔑 Seed
count[0] = 1, so subarrays starting at index 0 are counted.
⏱ Time O(n) · Space O(n)
- Subarray Sum Equals K · M — Base: count
- Contiguous Array · M — Map
0 → -1,1 → +1; longest subarray with sum 0 → store the first index of each prefix, answer =i - first[prefix] - Subarray Sums Divisible by K · M — Key = prefix
mod k, normalised((p % k) + k) % k; equal remainders pair up
HS3 Set-Based Sequence Start¶
- Base problem: Longest Consecutive Sequence · M
Put everything in a set. Only start counting from
xwherex - 1is not in the set, then extend upward.
🔑 Each sequence is walked exactly once (from its start), so the total work is
O(n)despite the inner loop.
⏱ Time O(n) · Space O(n)
HS4 Prefix and Suffix Products¶
- Base problem: Product of Array Except Self · M
Pass 1 left→right:
res[i] = product of everything to the left. Pass 2 right→left: multiply by a running product of everything to the right. No division, so zeros are fine.
⏱ Time O(n) · Space O(1) extra
Intervals¶
IV1 Sort by Start and Merge¶
Recognition: Combine overlapping ranges, or insert a range into an existing set.
Base problem: Merge Intervals · M
Sort by start; if cur.start ≤ last.end, set last.end = max(last.end, cur.end); else append.
🔑 After sorting by start, an interval can only overlap the last merged one.
⏱ Time O(n log n) · Space O(n)
- Merge Intervals · M — Base
- Insert Interval · M — Already sorted → no sort: copy all intervals ending before the new one, merge all overlapping ones into it, copy the rest.
O(n)
IV2 Sort by End and Keep Greedily¶
Recognition: "Maximum number of non-overlapping intervals" / "minimum removals" / "minimum arrows".
Core idea: Sort by end; always keep the interval that finishes earliest, since it leaves the most room.
Base problem: Non-overlapping Intervals · M
Keep an interval if start ≥ lastEnd, updating lastEnd; answer = n - kept.
⚠️ Sorting by start gives a wrong greedy here.
⏱ Time O(n log n) · Space O(1) extra
- Non-overlapping Intervals · M — Base
- Minimum Number of Arrows to Burst Balloons · M — Shoot at the first balloon's end; start a new arrow when
start > lastEnd(touching counts as overlapping, so>not≥)
IV3 Sweep Line for Overlap Counts¶
Recognition: "Maximum simultaneous X": rooms, passengers, active events.
Core idea: Turn intervals into +1 at start and -1 at end events; sort and sweep, tracking the running count. Or sort by start and keep a min-heap of end times.
Base problem: Meeting Rooms II (P) · M
Sort by start; pop heap tops with end ≤ start (room freed); push the new end; answer = max heap size.
⏱ Time O(n log n) · Space O(n)
- Meeting Rooms II (P) · M — Base
- Car Pooling · M — Difference array over stops (
+passengersat pickup,-passengersat drop-off); check no prefix exceeds capacity
Greedy¶
GD1 Extending the Frontier¶
Recognition: "Can I reach the end?", "minimum jumps", "split into the fewest segments"; each element extends how far you can go.
Core idea: Track the farthest reachable position; on reaching the end of the current region, commit to the next one.
Base problem: Jump Game · M
maxReach = max(maxReach, i + nums[i]); if i > maxReach at any point → unreachable.
⏱ Time O(n) · Space O(1)
- Jump Game · M — Base: feasibility
- Jump Game II · M — BFS in disguise:
curEnd= end of current level,farthest= best next; wheni == curEnd→jumps++,curEnd = farthest - Partition Labels · M —
end = max(last[c])over chars in the current segment; cut wheni == end
GD2 Running Surplus with Reset¶
- Base problem: Gas Station · M
If
total gas < total cost→-1. Otherwise run a tank balance; when it goes negative ati, restart fromi + 1.
🔑 If starting at
sfails atk, no station betweensandkcan succeed (they'd arrive with even less fuel), so skip them all.
⏱ Time O(n) · Space O(1)
GD3 Slot Counting Formula¶
- Base problem: Task Scheduler · M
Let
f= max task frequency,m= number of tasks with that frequency. Time =max(len(tasks), (f - 1) · (n + 1) + m).
🔑 The most frequent task defines
f-1gaps of widthn+1; every other task fits inside those gaps, or the answer is simply the task count.
⏱ Time O(len) · Space O(1)
GD4 Two-Pass Constraints¶
- Base problem: Candy · H
Pass left→right to satisfy "higher than left neighbour", pass right→left with
maxto satisfy "higher than right neighbour". Sum.
🔑 Two independent one-sided constraints can be satisfied separately and combined with
max.
⏱ Time O(n) · Space O(n)
Top-K and Two Heaps¶
TH1 Size-K Heap¶
Core idea: To keep the k largest, use a min-heap of size k (evict the smallest). To keep the k smallest, use a max-heap of size k.
Base problem: Kth Largest Element in an Array · M
Push each element; pop when size exceeds k; the top is the answer. Quickselect gives average O(n).
⏱ Time O(n log k) · Space O(k)
- Kth Largest Element in an Array · M — Base
- K Closest Points to Origin · M — Max-heap of size
kon squared distance (no sqrt needed)
TH2 Two Heaps for Median¶
Recognition: Median or "middle element" of a changing collection.
Base problem: Find Median from Data Stream · H
Max-heap lo (lower half) and min-heap hi (upper half). Add to lo, move lo's top to hi, then rebalance so len(lo) ≥ len(hi) and differ by ≤ 1. Median = lo.top or the average of both tops.
🔑 Every element in
lo≤ every element inhi, and sizes differ by at most 1.
⏱ Time O(log n) add, O(1) median · Space O(n)
- Find Median from Data Stream · H — Base
- Sliding Window Median · H — Elements leave the window → needs lazy deletion (hash of pending removals) or an ordered multiset
Tries¶
TE1 Basic Trie¶
Recognition: Many prefix queries, autocomplete, "shortest/longest prefix that is a word".
Base problem: Implement Trie (Prefix Tree) · M
Node = children[26] + isWord. insert/search/startsWith walk one char per step.
⏱ Time O(L) per operation · Space O(total chars)
- Implement Trie (Prefix Tree) · M — Base
- Replace Words · M — For each word, walk the trie and stop at the first
isWordnode (shortest root)
TE2 Trie with Wildcard DFS¶
- Base problem: Design Add and Search Words Data Structure · M
Search recursively; a
.branches into all children, a letter follows one child.
⚠️ Worst case with many wildcards is exponential in the wildcard count; typical inputs are small.
TE3 Trie plus Grid DFS¶
Recognition: Find many dictionary words in a grid (running Word Search once per word is too slow).
- Base problem: Word Search II · H Build a trie of all words. DFS from each cell while walking the trie; stop when the current prefix isn't in the trie. At a node with a stored word, record it and clear it (avoids duplicates). Prune empty trie branches.
🔑 The trie shares prefixes, so one DFS searches for all words at once.
⏱ Time O(mn · 4 · 3^(L-1)) worst case · Space O(total chars)
Matrix Manipulation¶
MX1 In-Place Matrix Transforms¶
Base problem: Rotate Image · M Clockwise 90°: transpose, then reverse each row. (Counter-clockwise: transpose, then reverse each column.)
⏱ Time O(n²) · Space O(1)
- Rotate Image · M — Base
- Set Matrix Zeroes · M — Use the first row and first column as marker storage; track separately whether the first row/column themselves had a zero.
O(1)space
MX2 Boundary Traversal¶
- Base problem: Spiral Matrix · M
Maintain
top, bottom, left, right; walk the four edges, shrinking after each.
⚠️ Re-check top ≤ bottom and left ≤ right before the third and fourth legs, or single-row/column matrices duplicate elements.
⏱ Time O(mn) · Space O(1) besides output
Classic Graph Problems¶
These are frequently practised classics. Most map to patterns covered earlier; only one needs a new pattern.
Classic Problems Mapped to Existing Patterns¶
- Number of Islands · M — GR2 — Count flood-fill starts
- Rotting Oranges · M — GR4 — Multi-source BFS, one level = one minute; return
-1if fresh oranges remain - Course Schedule · M — GR8 — Cycle check: processed count
== n - Course Schedule II · M — GR8 — Return the Kahn processing order (empty if a cycle)
- Word Ladder · H — GR5 — Bucket words by wildcard pattern (
h*t) to generate neighbours fast; bidirectional BFS optimises - Pacific Atlantic Water Flow · M — GR2 — Flood inward (uphill) from each ocean's border, intersect the two reachable sets
GR13 Clone Graph with Copy Map¶
- Base problem: Clone Graph · M
DFS/BFS with
map: old → new. On first visit create the clone and register it in the map before recursing into neighbours; later visits just returnmap[node].
🔑 The map is both the visited set and the way to wire cycles correctly.
⏱ Time O(V+E) · Space O(V)
Linked List Essentials¶
LE1 Reversal Patterns¶
Base problem: Reverse Linked List · E
prev = null; loop: next = cur.next; cur.next = prev; prev = cur; cur = next.
⏱ Time O(n) · Space O(1)
- Reverse Linked List · E — Base
- Reorder List · M — Middle (LL1) → reverse second half → interleave
- Reverse Nodes in k-Group · H — Check
knodes exist; reverse that block; reconnect to the previous tail and next block; leave a short tail untouched
LE2 Merging Lists¶
Base problem: Merge Two Sorted Lists · E Dummy head + tail pointer; attach the smaller head each step; append the leftover list.
- Merge Two Sorted Lists · E — Base.
O(m+n) - Merge k Sorted Lists · H — Min-heap of the
kheads, or divide-and-conquer pairwise merging.O(N log k)
LE3 Gap Pointer¶
- Base problem: Remove Nth Node From End of List · M
Dummy head; advance
fastbyn + 1; movefastandslowtogether untilfastis null;slow.next = slow.next.next.
🔑 Keeping a fixed gap of
nturns "from the end" into "from the front".
⏱ Time O(n) · Space O(1)
LE4 Copy with Random Pointer¶
- Base problem: Copy List with Random Pointer · M
Hashmap
old → newin two passes (create nodes, then setnext/random).O(1)space version: interleave copies after each original, setcopy.random = orig.random.next, then split the lists.
⏱ Time O(n) · Space O(n) (or O(1) interleaved)
Data Structure Design¶
DS1 Hashmap plus Linked List¶
Recognition:
O(1)get/put and an ordering (recency, frequency).
Base problem: LRU Cache · M
Hashmap key → node + doubly linked list ordered by recency (dummy head and tail). get: move node to front. put: update/insert at front; evict the tail's predecessor when over capacity.
🔑 The map gives
O(1)lookup; the list givesO(1)reorder and eviction.
⏱ O(1) per operation · Space O(capacity)
- LRU Cache · M — Base
- LFU Cache · H —
key → (value, freq),freq → ordered list of keys, plusminFreq; when theminFreqbucket empties after a touch,minFreq++. New key resetsminFreq = 1
DS2 Hashmap plus Array for Random Access¶
- Base problem: Insert Delete GetRandom O(1) · M
Array of values + map
value → index. Delete: swap the target with the last element, update that element's index, pop.
🔑 Swap-with-last makes array deletion
O(1).
DS3 Smaller Design Patterns¶
- Min Stack · M — Store
(value, minSoFar)on each push - Time Based Key-Value Store · M — Per key: list of
(timestamp, value)(timestamps arrive increasing) → binary search for the last timestamp≤ t - Binary Search Tree Iterator · M — Controlled in-order with a stack of left spine; amortised
O(1)next,O(h)space - Flatten Nested List Iterator · M — Stack of iterators (or reversed list); in
hasNext, unwrap until an integer is on top - Logger Rate Limiter (P) · E — Map
message → next allowed timestamp. Real rate limiters generalise to sliding window log, token bucket, or fixed window counters
Monotonic Deque¶
MD1 Sliding Window Extremum¶
Recognition: Max/min over every window, or a window condition involving max − min, or subarray sums with negatives.
Core idea: Keep a deque of indices whose values are monotone; the front is always the current extreme.
Blueprint:
1. Pop front if its index left the window.
2. Pop back while a[back] is worse than the new value.
3. Push the new index; read the front.
Base problem: Sliding Window Maximum · H
🔑 An element that is both older and smaller than a newcomer can never be the max again.
⏱ Time O(n) · Space O(k)
- Sliding Window Maximum · H — Base
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit · M — Two deques (max and min); shrink
lwhilemax - min > limit - Shortest Subarray with Sum at Least K · H — Deque over prefix sums (increasing). Pop front while
prefix[i] - prefix[front] ≥ k(record length); pop back whileprefix[back] ≥ prefix[i]. Handles negatives, unlike SW2
Minimum Spanning Tree¶
MS1 Kruskal and Prim¶
Recognition: "Connect all nodes at minimum total cost."
Core idea (Kruskal): Sort edges by weight; add an edge if it joins two different components (Union-Find, GR11); stop at n - 1 edges. Prim: grow one tree, always adding the cheapest edge leaving it (heap).
Base problem: Min Cost to Connect All Points · M
Complete graph with Manhattan distances. Dense graph → Prim in O(n²) without a heap, or Kruskal over all n² edges.
🔑 Cut property: the cheapest edge crossing any cut belongs to some MST.
⏱ Kruskal O(E log E) · Prim (dense) O(n²)
- Min Cost to Connect All Points · M — Base
- Connecting Cities With Minimum Cost (P) · M — Explicit edges; return
-1if fewer thann - 1edges were used (disconnected)
Tree Traversal and Construction¶
TC1 Through-Node Answer with Upward Gain¶
Recognition: The best path may bend at any node, but a parent can only extend one branch.
Core idea: DFS returns the best one-sided value to the parent, while a global variable records the best two-sided value through the current node.
Base problem: Diameter of Binary Tree · E
Return 1 + max(l, r) (height); update ans = max(ans, l + r).
⏱ Time O(n) · Space O(h)
- Diameter of Binary Tree · E — Base
- Binary Tree Maximum Path Sum · H — Child gain =
max(0, dfs(child))(drop negative branches);ans = val + l + r; returnval + max(l, r). Initialiseansto-∞for all-negative trees
TC2 BST Validation and Inorder Tricks¶
🔑 In-order traversal of a BST is strictly increasing.
- Validate Binary Search Tree · M — Pass
(low, high)bounds down (comparing only with the parent is a classic bug), or check the in-order sequence is strictly increasing - Kth Smallest Element in a BST · M — Iterative in-order, stop at the
k-th pop. For repeated queries, augment nodes with subtree sizes - Binary Tree Inorder Traversal · E — Iterative: push the left spine, pop, visit, go right. Morris traversal gets
O(1)space by temporarily threading predecessors' right pointers
TC3 Construction and Serialization¶
Base problem: Construct Binary Tree from Preorder and Inorder Traversal · M
Preorder's next element is the root; its position in inorder splits left/right subtrees. Precompute value → inorder index for O(1) splits.
⏱ Time O(n) · Space O(n)
- Construct Binary Tree from Preorder and Inorder Traversal · M — Base
- Serialize and Deserialize Binary Tree · H — Pre-order with explicit
nullmarkers; deserialize by consuming tokens recursively (or BFS level-order encoding). Markers remove the need for a second traversal
Binary Search Variants¶
BV1 Rotated Array¶
Recognition: Sorted array rotated at an unknown pivot.
Core idea: At every mid, at least one half is sorted. Decide which, then check whether the target lies in the sorted half.
Base problem: Search in Rotated Sorted Array · M
⚠️ With duplicates, worst case degrades to O(n).
⏱ Time O(log n) · Space O(1)
- Search in Rotated Sorted Array · M — Base
- Find Minimum in Rotated Sorted Array · M — Compare
a[mid]witha[hi]:>→lo = mid + 1; elsehi = mid
BV2 Matrix as Flattened Array¶
- Base problem: Search a 2D Matrix · M
Rows sorted and each row starts above the previous row's last element → binary search over
0..mn-1, mappingidx → (idx / n, idx % n).
⏱ Time O(log(mn)) · Space O(1)
BV3 Partition Search¶
- Base problem: Median of Two Sorted Arrays · H
Binary-search a cut
iin the shorter array; the cut in the longer array isj = (m + n + 1)/2 - i. Valid whenmaxLeft(A) ≤ minRight(B)andmaxLeft(B) ≤ minRight(A). Median comes from the boundary values.
🔑 The search is for the correct partition, not an element.
⏱ Time O(log min(m, n)) · Space O(1)
- Koko Eating Bananas · M — textbook example of BS2:
feasible(speed)=Σ ceil(pile / speed) ≤ h, withlo = 1,hi = max(piles)
Bit Manipulation¶
BM1 XOR Cancellation¶
🔑
x ^ x = 0andx ^ 0 = x; XOR is commutative and associative, so pairs cancel.
- Single Number · E — XOR everything; only the unpaired value survives.
O(n)/O(1) - Missing Number · E — XOR all indices
0..nwith all values (or usen(n+1)/2 - sum)
BM2 Bit Counting Tricks¶
🔑
n & (n - 1)clears the lowest set bit;n & -nisolates it.
- Number of 1 Bits · E — Loop
n &= n - 1, counting iterations - Counting Bits · E —
dp[i] = dp[i >> 1] + (i & 1)(ordp[i & (i-1)] + 1)
Bitmask and Digit DP¶
BD1 Bitmask DP over Subsets¶
Recognition:
n ≤ ~20, "assign/visit/partition a set of items optimally".
State: dp[mask] (or dp[mask][last]) = best result having already handled the items in mask. Transition: add one item not in the mask. Order: increasing mask.
Base problem: Minimum Number of Work Sessions to Finish the Tasks · M
dp[mask] = (sessions, timeUsedInLastSession) minimised lexicographically; add task i: if it fits, same session; otherwise open a new one.
⏱ Time O(2ⁿ · n) · Space O(2ⁿ)
- Minimum Number of Work Sessions to Finish the Tasks · M — Base
- Find the Shortest Superstring · H — TSP-style
dp[mask][last]with precomputed pairwise overlaps; reconstruct the order.O(2ⁿ · n²)
BD2 Digit DP¶
Recognition: "Count numbers in
[0, N]with a digit property."
State: dp(pos, mask-or-property, tight, started). Walk digits from most significant; tight = prefix equals N's prefix so far (digit limited); started = leading zeros have ended.
- Base problem: Count Special Integers · H
Count numbers
≤ Nwith all distinct digits;mask= digits already used.
⚠️ Memoise only the non-tight, started states; handle leading zeros with started.
⏱ Time O(len · 2¹⁰ · 10) · Space O(len · 2¹⁰)
Math and Number Theory¶
MT1 Fast Exponentiation¶
- Base problem: Pow(x, n) · M
Square-and-multiply: if
nis odd multiply result byx;x *= x;n >>= 1. For negativen, invertxand negaten.
⚠️ Convert n to a 64-bit integer first; -INT_MIN overflows.
⏱ Time O(log n) · Space O(1)
MT2 Sieve of Eratosthenes¶
- Base problem: Count Primes · M
Boolean array; for
ifrom 2 whilei·i < n: if prime, mark multiples starting ati·i.
⏱ Time O(n log log n) · Space O(n)
MT3 GCD and Modular Arithmetic¶
🔑
gcd(a, b) = gcd(b, a % b),O(log min(a,b)). For modular answers, reduce after every multiply and use 64-bit intermediates; modular inverse for a prime modulus isa^(p-2).
- Find Greatest Common Divisor of Array · E —
gcd(min, max) - Greatest Common Divisor of Strings · E — If
s1 + s2 != s2 + s1→""; else prefix of lengthgcd(len1, len2)
String Algorithms¶
SA1 Expand Around Center¶
Base problem: Longest Palindromic Substring · M
For each index, expand for odd (i, i) and even (i, i+1) centers while chars match; track the best.
⏱ Time O(n²) (Manacher O(n)) · Space O(1)
- Longest Palindromic Substring · M — Base
- Palindromic Substrings · M — Count every successful expansion instead of tracking the longest
SA2 KMP Prefix Function¶
Recognition: Substring search without re-scanning, or "longest proper prefix that is also a suffix".
Core idea: lps[i] = length of the longest proper prefix of s[0..i] that is also a suffix. On mismatch, fall back to lps[j-1] instead of restarting.
Base problem: Find the Index of the First Occurrence in a String · E
⏱ Time O(n + m) · Space O(m)
- Find the Index of the First Occurrence in a String · E — Base
- Longest Happy Prefix · H — Answer =
s[:lps[n-1]] - Repeated Substring Pattern · E — Repeats iff
lps[n-1] > 0andn % (n - lps[n-1]) == 0(orsoccurs in(s+s)[1:-1])
SA3 Rolling Hash¶
Base problem: Longest Duplicate Substring · H
Binary search the length L (BS2: if a duplicate of length L exists, so does one of length L-1); check each L with a Rabin–Karp rolling hash in O(n); verify matches to rule out collisions.
🔑 Rolling hash updates in
O(1): remove the leading char, shift, add the new char (mod a large prime).
⏱ Time O(n log n) expected · Space O(n)
- Longest Duplicate Substring · H — Base
- Repeated DNA Sequences · M — Fixed length 10; a set of substrings is enough (or a 2-bit-per-char integer encoding)
SA4 Expression and String Parsing¶
- Basic Calculator II · M — Read number, apply the previous operator:
+/-push±num;*//modify the stack top; answer = stack sum.O(n) - String to Integer (atoi) · M — Skip spaces → sign → digits → clamp to 32-bit before overflowing
Advanced Data Structures and Graph Variants¶
Less frequent patterns that are still worth knowing.
AD1 Fenwick Tree¶
Recognition: Point updates with range-sum queries, or counting "how many smaller/larger elements so far".
Base problem: Range Sum Query - Mutable · M
Fenwick: update(i, delta) walks i += i & -i; query(i) walks i -= i & -i; range sum = query(r) - query(l-1).
⏱ Time O(log n) per op · Space O(n)
- Range Sum Query - Mutable · M — Base (segment tree also works, and extends to range min/max)
- Count of Smaller Numbers After Self · H — Coordinate-compress values; scan right to left, query the count of smaller values already inserted, then insert. (Merge sort counting also works)
AD2 Shortest Path with Limits¶
- Network Delay Time · M — Plain Dijkstra (GR9); answer = max distance, or
-1if any node is unreachable - Cheapest Flights Within K Stops · M — Bellman-Ford limited to
k+1rounds, relaxing from a copy of the previous round's distances; or Dijkstra/BFS with state(node, stops)
⚠️ Pruning Dijkstra by node alone is wrong when there's a stop limit; a costlier path with fewer stops may still be needed.
AD3 Random Sampling¶
- Linked List Random Node · M — Reservoir sampling (k = 1): replace the kept node with the
i-th node with probability1/i - Random Pick with Weight · M — Prefix sums of weights; pick a random integer in
[1, total]and binary search the first prefix≥it
Concurrency Basics¶
Recognition: Threads must run in a fixed order, alternate, or form groups.
Core idea: Use primitives to encode "B may not start until A finishes": semaphores, mutex + condition variable, events, or barriers.
- Print in Order · E — Two semaphores/events:
secondwaits forfirst,thirdwaits forsecond - Print FooBar Alternately · M — Two semaphores handing the turn back and forth
- Building H2O · M — Semaphore of 2 for hydrogen, 1 for oxygen, plus a barrier of 3 so each molecule releases together
⚠️ Concurrency problems are language-specific and are usually practised separately from standard DSA.
Coverage Check¶
| Section | Questions |
|---|---|
| Arrays and Two Pointers | 9 |
| Sliding Window | 4 |
| Stacks | 6 |
| Binary Search | 4 |
| Linked Lists | 7 |
| Trees | 9 |
| Heaps | 4 |
| Backtracking | 13 |
| Graphs | 33 |
| Dynamic Programming | 55 |
| SQL | 25 |
| More Patterns for Revision (19 sections) | 98 |
| Total | 267 |