Pattern Explorer
The 100 patterns that show up in interviews
Every ProgramAlpha exercise maps to one of these patterns. Learn the pattern and the unfamiliar problem becomes familiar.
Learn one pattern a week, not forty problems a day
Pick a pattern below and read its 3 steps. Then solve the linked problems in the lab — each one reuses what you just learned. Two or three patterns in, the repetition answers itself.
- 1Read the pattern card
- 2Solve its mapped problems
- 3Revisit it on the next logical problem
Family
Difficulty
100 of 100 patterns
Arrays & Hashing
Hash Map Lookup
Store what you have seen so far so future questions are answered in constant time.
a.k.a. hashtable, dictionary, hashmap
Applies to
O(1) membership and pairing problems
- Decide the key that uniquely describes past state.
- Build the entry before or after each lookup, depending on the question.
- Return "the thing I needed earlier" when the map answers it.
Arrays & Hashing
Frequency Counting
Count every item first, then let the counts answer comparison, majority and top-k questions.
a.k.a. counts, letter counts
Applies to
Counting occurrences before deciding about a collection
- Walk the input once building value → count.
- Compare counts when the problem asks about equality or balance.
- Read the counts out in the shape the problem's answer expects.
Arrays & Hashing
Prefix Sums & Products
Precompute running totals so any range is a difference of two prefixes.
a.k.a. prefix, cumulative, precompute
Applies to
Range queries over static arrays
- Build the cumulative array in one pass.
- Express the range answer as prefix[r] − prefix[l−1].
- Watch for off-by-one and integer overflow.
Arrays & Hashing
Running Min / Max in One Pass
Carry one running candidate while you walk, so the best answer is always available at the end.
a.k.a. rolling min, tracking extrema
Applies to
Best-so-far decisions over time
- Initialise the running value from the first element.
- Update it when the new element beats the candidate.
- Use the running value to answer the follow-up question each step.
Arrays & Hashing
Cyclic Sort
Swap each value into its index slot in O(1) space; whatever is out of place is the anomaly.
a.k.a. in-place index sort, 1..n placement
Applies to
Arrays of 1..n with one missing or duplicate
- While cycling, swap a[i] to position a[i]−1 whenever i isn't already correct.
- Advance only when the slot holds the right value.
- After one pass the misplaced element identifies the missing or duplicate.
Arrays & Hashing
Dutch National Flag
Keep low, mid and high pointers and partition three buckets in-place in one sweep.
a.k.a. 3 partition, sort colors
Applies to
Sorting three distinct values with one pass
- Left groups the low value, right groups the high value, mid scans the middle.
- Swap mid with left or right so each bucket stays contiguous.
- Stop mid crossing the right pointer; the array is sorted in three zones.
Arrays & Hashing
Boyer-Moore Majority Vote
Pair candidates against each other; the majority survives every cancellation.
a.k.a. majority element, vote counting
Applies to
Finding an element present more than n/2 times
- Keep a candidate and a counter that starts at zero.
- Increment when the value matches the candidate, else decrement.
- When the counter hits zero, adopt the current value as the candidate.
Arrays & Hashing
Duplicate Detection via Set
A set answers 'seen before?' in O(1); the second sighting is usually the answer.
a.k.a. contains duplicate, seen set
Applies to
Any question that asks 'has this appeared before?'
- Add each element to the set as you meet it.
- If Add returns false, a duplicate exists — act immediately.
- At the end an empty-duplicate scan means every element was unique.
Arrays & Hashing
Index Marking & Sign Flipping
Use the array itself as the visited set by flipping the sign at each value's index.
a.k.a. sign flip, negation marking
Applies to
Detecting duplicates or missing values in bounded arrays in place
- For each value v, inspect index |v|−1.
- Flip the sign there; a negative on revisit means the value is a duplicate.
- Value-range guaranteed ≤ n makes index marking safe.
Arrays & Hashing
Difference Array
Record deltas at range boundaries instead of touching every overlapped cell.
a.k.a. range add, diff array
Applies to
Many range-update queries answered at the end
- For each range [l, r] with delta d, add d at l and subtract d at r+1.
- After all ranges, compute the prefix sum of the diff array.
- The running total at index i is the true value there.
Arrays & Hashing
Canonical Form Grouping
Reduce each item to a canonical key, then group identical keys — the whole trick.
a.k.a. normalise then group, signature
Applies to
Grouping items that share a normalised shape
- Decide the canonical form: sorted string, char counts, or normalised encoding.
- Map canonical key → list of items.
- Return the groups; anything in the same bucket is equivalent.
Two Pointers
Two Pointers
Move a left and right pointer inward (or side-by-side) to avoid nested loops.
a.k.a. 2 pointers, pointer
Applies to
Sorted arrays and linked lists
- Start pointers at opposite ends (or the same head).
- Apply one rule that decides which pointer moves.
- Stop when the pointers meet or one runs off the end.
Two Pointers
Opposite-Ends Scanning
Start at both ends; every step moves exactly one end based on one comparison rule.
a.k.a. left/right sweep, inward scan
Applies to
Sorted arrays where answers sit at both extremes
- Compare the pair under both pointers against the target.
- Move the pointer whose move can only improve the direction you need.
- Terminate when the pointers cross.
Two Pointers
Same-Direction (Runner) Pointers
One pointer runs ahead; the other chases to maintain an invariant gap.
a.k.a. two runners, fast behind slow
Applies to
Arrays and lists where a gap between two cursors is the answer
- Advance one pointer first to create the initial gap.
- Move both together, checking the invariant at the rear pointer.
- The gap width encodes the answer you report.
Two Pointers
Fast & Slow Pointers
A fast pointer moves twice as fast as a slow one; a cycle forces them to collide.
a.k.a. tortoise, hare, cycle detection
Applies to
Linked lists, cycles, middle nodes
- Advance slow by 1 and fast by 2 each step.
- If they meet inside the list, a cycle exists.
- Fast reaching the end proves the list is acyclic.
Two Pointers
Palindrome & Mirror Scan
Either compare mirrored ends or expand outward from a centre — never compare all pairs.
a.k.a. mirror scan, expand around centre
Applies to
Palindromic substrings and symmetric checks
- Pick the centre: a single char (odd) or a gap (even).
- Expand both directions while characters mirror.
- Record each stretched palindrome; the longest wins.
Two Pointers
Reverse Trick & In-place Rewrites
Three reverses — whole, left part, right part — rotate an array without extra space.
a.k.a. reverse then mutate, rotate by reverse
Applies to
Rotations, in-place transforms, and swap-heavy edits
- Normalise the rotation amount modulo the length.
- Reverse the whole array, then each partition separately.
- The result is the rotation, done in O(1) space.
Sliding Window
Sliding Window
Grow a window with the right edge, shrink with the left, and track a property of the window.
a.k.a. window, substring
Applies to
Contiguous subarrays / substrings
- Expand the right edge to include a new element.
- While the window violates the constraint, advance the left edge.
- Record the answer at the moment the window is valid.
Sliding Window
Fixed-Size Window
Slide a window of constant size; update the aggregate by evicting one and adding one.
a.k.a. k-length window, constant window
Applies to
Problems with a window of a known length k
- Build the first window of size k and aggregate it.
- Slide right: remove a[left], add a[right].
- Evaluate the aggregate at each position.
Sliding Window
Variable Window — Longest
Expand to make progress, shrink to restore validity, and keep the max valid length.
a.k.a. expand contract, valid longest
Applies to
Longest subarray/substring satisfying a constraint
- Track counts so you know when the window becomes invalid.
- Shrink from the left until valid again.
- Update the best length every time the window is valid.
Sliding Window
Variable Window — Minimum
Expand until every target is present, then shrink to minimise while staying valid.
a.k.a. enclosing window, minimum covering
Applies to
Smallest window containing all targets
- Grow the right edge until all required conditions are met.
- Try shrinking the left edge while the window stays valid.
- Track the window with the smallest length seen.
Sliding Window
Count of Valid Windows
For every valid window ending at r, all sub-windows ending at r are valid — count them in bulk.
a.k.a. subarray count, windows satisfying constraint
Applies to
Counting subarrays by a validity rule
- Run a standard left-shrinking window.
- When valid at r, add (r − left + 1) to the answer.
- That one arithmetic brainhands every sub-window ending at r.
Stack & Monotonic Queue
Bracket & Parse Stack
Push toward matching, pop toward closing; a stack enforces reverse order naturally.
a.k.a. paren stack, matching stack
Applies to
Symbols that must close in reverse order
- Push the expected closer for each opener.
- On a closer, it must equal the top of the stack — else invalid.
- The stack must be empty at the end.
Stack & Monotonic Queue
Monotonic Stack
Keep the stack sorted; pop dominated entries so the extreme stays answerable in O(1).
a.k.a. next greater, next smaller
Applies to
Next greater/smaller and dominance problems
- While the candidate dominates the back, pop it.
- The element you pop now resolves its 'next greater' to the candidate.
- Push the candidate; indices live in the stack, values in the array.
Stack & Monotonic Queue
Monotonic Deque (Window Extremes)
A deque holding candidates in sorted order gives the window extreme in O(1).
a.k.a. deque, window max deque
Applies to
Sliding window extremes in O(n)
- Pop the back while it can never beat the new element.
- Pop the front when it leaves the window.
- The front is always the extreme of the current window.
Stack & Monotonic Queue
Min-Stack / Two-Stack Trick
Store the current minimum alongside each pushed value so history never lies.
a.k.a. tracking min, paired stack
Applies to
O(1) min query alongside O(1) push/pop
- Push (value, min-so-far) pairs or a parallel min stack.
- On pop, discard that level's min too.
- Peek the min stack for the running minimum.
Stack & Monotonic Queue
Queue & Stack Interop
Two stacks — one for enqueue, one for dequeue — give FIFO with amortised O(1) ops.
a.k.a. stack to queue, amortised queue
Applies to
Building one abstract data type from another
- Push new items onto the 'in' stack.
- Move items to the 'out' stack only when it is empty.
- Pop from 'out' for dequeue; it reverses order exactly once.
Stack & Monotonic Queue
Nested Depth & Scores
The stack height at any point is the nesting depth; scores compound as you descend.
a.k.a. depth tracking, nesting level
Applies to
Parsing nesting levels and weighted nesting values
- Increase a depth counter when opening, decrease on closing.
- Record the maximum depth or apply the nesting weight.
- Read the result once the whole input is consumed.
Binary Search
Binary Search
Halve the search space each step by comparing against the middle.
a.k.a. bs, bisect
Applies to
Sorted (or monotonic) search spaces
- Low, high, and a loop invariant that the answer stays inside.
- Compare the middle; decide which half to keep.
- Watch the boundary so the loop always terminates.
Binary Search
First / Last Bound (Lower & Upper)
Decide which side to keep even on equality to bias toward the first or the last match.
a.k.a. first occurrence, last occurrence, lower bound
Applies to
Leftmost/rightmost match in a sorted array
- On equality, keep the left half for first-index searches.
- Keep the right half for last-index searches.
- Return the surviving boundary after the loop.
Binary Search
Search in a Rotated Array
Compare the middle against the ends to decide which side is sorted, then search normally.
a.k.a. pivot search, rotate detect
Applies to
Sorted arrays rotated at an unknown pivot
- Compute mid; one half is always fully sorted.
- If the target lies in the sorted half's range, search it.
- Otherwise drop it and search the other half.
Binary Search
Binary Search on the Answer
Binary search the value space of the answer; each mid is accepted or rejected by a check.
a.k.a. feasibility search, minimax search
Applies to
Optimisation problems with a monotonic feasibility check
- Set low/high to the tightest possible answer bounds.
- Run a feasibility check on mid that is monotone in mid.
- Narrow toward the best feasible answer.
Binary Search
Median & Partition Search
Binary search a partition point in the smaller array so both sides are balanced.
a.k.a. kth element, partition around cut
Applies to
Median / k-th element of two sorted arrays
- Binary search the cut in the shorter array.
- Derive the other cut from total size.
- Verify cross-order: every Left ≤ every Right, then read the median.
Binary Search
Peak & Local Minima Search
Compare the middle with its neighbour; the bigger side is guaranteed to hold a peak.
a.k.a. peak element, bitonic
Applies to
Finding a local extremum in O(log n)
- Compare mid with mid+1.
- If the right neighbour is larger, a peak lies to the right.
- Otherwise a peak lies left (or at mid).
Binary Search
Binary Search in 2D
Start at a corner and walk one direction at a time — each step halves the remaining matrix.
a.k.a. grid binary search, staircase search
Applies to
Row- and column-sorted matrices
- Start at the top-right (or bottom-left) corner.
- Compare with the target: move down if larger, left if smaller.
- Match exactly or fall off the matrix.
Binary Search
Search a Monotonic Function
When f(i) is monotone, the first true index is a binary search over the index space.
a.k.a. inversion search, value in function
Applies to
Finding an index where a predicate flips
- Define the predicate that is false then true as the index grows.
- Binary search for the first index where it turns true.
- Handle the all-false and all-true edges explicitly.
Linked List
Reverse Linked List
Rewire each node's next pointer to the previous node in one pass.
a.k.a. list reverse, reverse in place
Applies to
Reversing singly-linked structures
- Keep prev, curr, next pointers.
- Point curr to prev, then walk all three forward.
- When curr is null, prev is the new head.
Linked List
Merge Sorted Linked Lists
A dummy head and a tail walker zip two sorted lists into one.
a.k.a. merge lists, zipper merge
Applies to
Merging sorted sequences without extra arrays
- Create a dummy node to own the result.
- Link the smaller tail, advance that input.
- Attach whatever remains; return dummy.next.
Linked List
Sentinel & Remove-Nth Style
A dummy head removes the null/head edge cases of every deletion problem.
a.k.a. dummy head, remove nth
Applies to
Deletions at a computed position
- Read the position with a runner.
- Advance a second pointer until the runner reaches the end.
- Unlink the target; return dummy.next.
Linked List
Two Pointers on Lists
Fast/slow and offset pointers locate positions without counting twice.
a.k.a. list pointers, middle of list
Applies to
Interleaving, finding middles and k-th-from-end
- Run one pointer ahead by k steps.
- Advance both until the lead pointer nulls out.
- The laggard is exactly k from the end.
Linked List
Hash + Doubly-Linked List (LRU)
Couple a hash map of keys with a doubly-linked recency list of nodes.
a.k.a. lru, eviction list
Applies to
O(1) access plus O(1) recency moves
- Hash map gives O(1) lookup of a list node.
- Move a node to the front on access — O(1) with a doubly-linked list.
- Evict the tail when the capacity is exceeded.
Linked List
Cycle Entry Point
After detection, move slow to head and step both one at a time; they meet at the cycle entry.
a.k.a. cycle head, tortoise equation
Applies to
Finding where a linked-list cycle begins
- Detect the cycle with fast/slow to find any meeting point.
- Reset slow to the head; keep fast at the meeting point.
- Advance both by one — the meeting node is the cycle's start.
Trees & BSTs
Traversal Order Mastery
Pre/in/post order decide when the node's own work happens relative to its children.
a.k.a. preorder, inorder, postorder
Applies to
Any order-sensitive tree work
- Pre: root → left → right.
- In: left → root → right (a BST becomes sorted).
- Post: left → right → root (children first is ideal for freeing or summing).
Trees & BSTs
Level-Order / Tree BFS
Process nodes a level at a time: drain the queue's current size, enqueue children.
a.k.a. bfs tree, level traversal
Applies to
Row-by-row tree processing
- Seed the queue with the root.
- For each level, process exactly the current queue size.
- Each drained group is one level's nodes.
Trees & BSTs
Path Sums & Maximum Path
Post-order recursion returns the best value each subtree can offer upward.
a.k.a. root to leaf sum, max path
Applies to
Summing or maximising values along tree paths
- At each node, combine the best child contributions.
- Compare the node's own arc against the running global best.
- Return only the single best downward branch to the parent.
Trees & BSTs
Depth, Count & Diameter
One post-order pass returns subtree depth/height/size to its caller.
a.k.a. tree height, diameter, size
Applies to
Structural metrics of a tree
- Base case: empty subtree has height 0.
- Combine child heights, adding 1 for the current edge.
- The maximum depth-1 + depth-2 + 2 across nodes is the diameter.
Trees & BSTs
BST Search & Range Queries
Follow the ordering property to locate or prune subtrees in O(height).
a.k.a. bst range, bst path
Applies to
Ordered queries over a binary search tree
- Compare the target with the current node's value.
- Prune the subtree that cannot contain the answer.
- Aggregate values within the range by skipping out-of-range branches.
Trees & BSTs
Lowest Common Ancestor
A node is the LCA when it is one target, or when one target sits in each subtree.
a.k.a. lca, ancestor node
Applies to
Finding the deepest node that is an ancestor of both targets
- Search both sides recursively for the two targets.
- If both children return a hit, the current node is the LCA.
- Otherwise propagate the non-null hit upward.
Trees & BSTs
Build Tree from Traversals
For trees where a node splits its remaining set, use type 1 in type 2 analogy: one traversal picks the root, the other splits the range.
a.k.a. construct tree, preorder inorder
Applies to
Rebuilding a tree from its traversals
- Take the next root from the preorder.
- Find its index in the inorder to split left/right ranges.
- Recurse with the shrunk ranges.
Trees & BSTs
Serialize / Deserialize Tree
A preorder walk with explicit null markers encodes the tree unambiguously.
a.k.a. tree encoding, preorder encode
Applies to
Persisting tree structure to a string and back
- Serialize with preorder, emitting a marker for null.
- Deserialize by consuming tokens and rebuilding left/right.
- The marker list keeps the shape recoverable.
Tries & Strings
Trie / Prefix Tree
Share prefixes across stored strings so lookups cost only the pattern's length.
a.k.a. prefix tree, autocomplete tree
Applies to
Prefix lookups, word lists, auto-complete
- Node holds children (per char) and a wordEnd flag.
- Insert walks/creates child by child.
- Search walks the prefix; if it ends on a wordEnd, the full word exists.
Tries & Strings
Anagram Signature
Anagram = identical letter signature; sort or count to build the key.
a.k.a. anagram key, sorted key
Applies to
Detecting or grouping anagrams
- Build a signature per string: sorted chars or 26 counts.
- Compare signatures to test equality.
- Group by signature to collect all anagram classes.
Tries & Strings
Substring Match (KMP / Rolling Hash)
Precompute a failure/hash table so the backtrack on mismatch is O(1) amortised.
a.k.a. pattern search, rabin-karp, kmp
Applies to
Finding a pattern inside text efficiently
- Precompute the failure table (longest proper prefix = suffix).
- Slide the pattern pointer; on mismatch fall back via the table.
- A completed pattern window is a match; report and continue.
Tries & Strings
Palindrome Checks & Permutations
A palindrome needs at most one character with an odd count.
a.k.a. palindrome permutation, palindrome by rearrange
Applies to
Can a string be rearranged into a palindrome
- Count character frequencies.
- Count how many frequencies are odd.
- That count must be 0 or 1 for a rearrangement to exist.
Tries & Strings
Character Frequency Tracking
Track counts inside a window plus a 'unique' counter to test validity in O(1).
a.k.a. char window counts, frequency window
Applies to
Window problems measured in letter counts
- Keep char counts for the current window.
- Track the number of chars that meet the condition.
- Add/remove one char per slide and update the counters.
Tries & Strings
String Transforms
Read the rule, write with a StringBuilder, and understand that strings are immutable.
a.k.a. run length, string compression, zigzag
Applies to
Rewriting a string under a deterministic rule
- Parse the rule: grouping, spacing, or rotating.
- Write the output with a StringBuilder.
- Verify against the formatted example before submitting.
Heaps & Priority Queues
Heaps / Priority Queues
A heap keeps the extreme element accessible in O(log n) per push/pop.
a.k.a. priority queue, top k
Applies to
Repeated minima/maxima, top-k queries, streaming
- Choose min-heap vs max-heap for the invariant you need.
- For top-k, cap the heap at size k.
- For running medians, pair a min-heap and a max-heap.
Heaps & Priority Queues
Top-K Selection
Cap a min-heap of size k so the weakest candidate is evicted, not the strongest.
a.k.a. k most frequent, k largest
Applies to
The k biggest/frequent elements of a stream
- Push each candidate into a size-k min-heap.
- Evict the top when the heap exceeds k.
- The surviving k elements are the top-k.
Heaps & Priority Queues
Running Median (Two Heaps)
A max-heap for the lower half and a min-heap for the upper half balance around the median.
a.k.a. median heap, max-heap min-heap
Applies to
Streaming medians and percentiles
- Insert into the appropriate half heap.
- Rebalance so sizes differ by at most one.
- The median is the top of the larger (or the mean of both tops).
Heaps & Priority Queues
Merge K Sorted Streams
A heap of the heads merges k lists in O(n log k).
a.k.a. merge k, multiway merge
Applies to
Merging many sorted sequences
- Heap the current head of every list, keyed by value.
- Pop the smallest, link it into the result.
- Push that list's next node and repeat.
Heaps & Priority Queues
Greedy with Heap Scheduling
Take the most pressing job each tick — a heap picks it in O(log n).
a.k.a. task scheduler, meeting rooms heap
Applies to
Scheduling with availability constraints
- Load tasks into a max-heap by demand.
- Consume per time unit, deferring cooldown items.
- Count units until the heap and cooldown queue are empty.
Backtracking & Recursion
Backtracking
Build solutions incrementally, and undo the last choice when a branch fails.
a.k.a. dfs state, recursion, permutations
Applies to
Enumerate all configurations (combos, subsets, paths)
- Decide the decision variables and the base case.
- Make a choice, recurse, then undo the choice.
- Prune branches early when a prefix is already invalid.
Backtracking & Recursion
Subsets & Combinations
At each element decide include or skip; the recursion states enumerate all groups.
a.k.a. powerset, pick or skip
Applies to
Every subset or fixed-size group of a set
- For subsets: two branches per element (take / skip).
- For combinations: keep an index so you only move forward.
- Snapshot the list when reaching a target length or the end.
Backtracking & Recursion
Permutations & Orderings
Swap-in / used-flag recursion explores every ordering exactly once.
a.k.a. arrangements, all orderings
Applies to
Every ordering of a set (with or without duplicates)
- Track used positions or swap to avoid repeats.
- At full length, snapshot the permutation.
- Sorting and skipping equal neighbours removes duplicate permutations.
Backtracking & Recursion
Constraint Pruning
Check every new placement against the constraints before recursing deeper.
a.k.a. n queens, candidate filtering
Applies to
Search spaces with hard row/column/diagonal rules
- Keep sets for used rows, columns and diagonals.
- Skip any placement that collides.
- Recurse only into valid placements until the board fills.
Backtracking & Recursion
Pick / Not-Pick Decision Recursion
Every state forks on include/exclude; memoise the state to stop re-exploring it.
a.k.a. choice tree, take or leave
Applies to
Optimum-search problems framed as choices
- Define state = position + what changes (capacity, target).
- Branch on take / skip and take the max or min.
- Cache states so each is solved once.
Backtracking & Recursion
Recursion & Call-Stack Mapping
Draw the recursion tree: branching factor and depth predict calls and stack usage.
a.k.a. recursion depth, stack trace
Applies to
Understanding and bounding recursive solutions
- Count the branching factor and the depth of the tree.
- Calls = branches^depth; stack use = depth, not calls.
- Convert to iteration if depth risks stack overflow.
Graphs & Union-Find
Tree / Graph DFS
Explore as deep as possible along each branch before backtracking.
a.k.a. dfs, recursion tree
Applies to
Connected components, paths, tree traversals
- Process the current node, then recurse into neighbours.
- For graphs, mark visited to prevent revisits.
- Pick pre-order or post-order work depending on what must happen first.
Graphs & Union-Find
Breadth-First Search
Process the frontier a layer at a time using a queue.
a.k.a. bfs, queue
Applies to
Shortest paths (unweighted), level-order, flood fill
- Seed the queue with start nodes.
- Drain one layer, enqueueing all neighbours.
- The layer count measures distance, so first arrival is shortest.
Graphs & Union-Find
Matrix Traversal
Treat the grid as a graph; each cell is a node with up/down/left/right edges.
a.k.a. grid, islands
Applies to
2D grids and board problems
- Check bounds before any neighbour visit.
- Mark cells visited (often by mutation) to avoid revisits.
- Flood-fill via BFS or DFS to explore one component.
Graphs & Union-Find
Union-Find / Disjoint Set
Union-Find tracks connected components near-instant amortised time.
a.k.a. disjoint set, dsu, connectivity
Applies to
Connectivity, dynamic grouping, cycle checks
- Each node starts in its own set.
- Union merges two sets; Find returns the representative.
- Two nodes in the same set ⇒ a cycle or shared component.
Graphs & Union-Find
Cycle Detection in Graphs
Visited + inStack marks expose back edges; union-find catches undirected cycles.
a.k.a. detect cycle, back edge
Applies to
Whether a directed/undirected graph has a cycle
- DFS with a recursion stack: on return to a node still on it, cycle.
- For undirected graphs, skip the edge back to the parent.
- Union-find answers the same question incrementally during building.
Graphs & Union-Find
Bipartite / Two-Colour Check
Colour alternately during BFS/DFS; a same-colour edge disproves bipartiteness.
a.k.a. 2 colour, graph colouring
Applies to
Can vertices split into two sets with no intra-set edges
- Colour start nodes red.
- Neighbours always get the opposite colour.
- A neighbour already same-coloured is an immediate contradiction.
Graphs & Union-Find
Multi-Source BFS
Enqueue every source at distance 0 together; BFS then computes nearest-source distances.
a.k.a. 0-1 bfs, starting set
Applies to
Distance from the nearest of many sources
- Seed the queue with all sources at distance 0.
- Expand level by level, skipping visited cells.
- Each cell inherits the distance of the layer that first reaches it.
Advanced Graphs
Topological Sort
Order nodes so every edge points forward; only acyclic graphs have an order.
a.k.a. topo, prereq, kahn
Applies to
Ordering tasks with dependencies
- Count in-degrees. Enqueue all nodes with zero.
- Process the queue, decrementing neighbours.
- Fewer than N nodes processed ⇒ a cycle exists.
Advanced Graphs
Shortest Path — Dijkstra
A priority queue always relaxes the currently-cheapest frontier node.
a.k.a. weighted shortest, priority bfs
Applies to
Shortest paths in graphs with non-negative weights
- Distances start at infinity; start node is 0.
- Pop the cheapest node and relax its edges.
- Stop when the target is popped — no shorter route exists.
Advanced Graphs
Minimum Spanning Tree
Kruskal: sort edges, union if they don't already connect. Prim: grow from a root via a heap.
a.k.a. kruskal, prim
Applies to
Cheapest connected subgraph spanning all nodes
- Sort edges by weight (Kruskal) or seed a heap (Prim).
- Add an edge only when it connects two different components.
- Stop at V−1 edges: that is the spanning tree.
Greedy & Intervals
Interval Technique
Sort intervals, then walk them greedily, merging or counting as required.
a.k.a. merge intervals, meeting rooms
Applies to
Scheduling and overlapping ranges
- Sort by start time.
- Keep a running current interval and extend when the next overlaps.
- Emit or branch when the next interval begins after the current ends.
Greedy & Intervals
Greedy Choice & Exchange Argument
Pick the move that looks best now, then prove swapping any other in cannot improve.
a.k.a. locally optimal, exchange argument
Applies to
Optimisation where the best local move is globally optimal
- State the greedy rule precisely.
- Justify with an exchange argument that any optimal solution can adopt the greedy pick.
- Implement the rule in one pass where possible.
Greedy & Intervals
Interval Scheduling (Max Non-Overlap)
Sort by end time and always take the interval that finishes first.
a.k.a. meeting rooms, max meetings
Applies to
Maximising the number of non-overlapping intervals
- Sort by end time.
- Take an interval if its start is after the last taken end.
- Update the last end and count it.
Greedy & Intervals
Merge Overlapping Intervals
Sort by start; extend the current range whenever the next start is inside it.
a.k.a. overlap merge, union ranges
Applies to
Collapsing ranges that touch or overlap
- Sort intervals by start.
- If the next start ≤ current end, extend current end.
- Else emit current and start a new one.
Greedy & Intervals
Sweep Line / Events
Turn ranges into start/end events; sweep sorted events and track active count.
a.k.a. event sweep, skyline
Applies to
Counting active ranges across time
- Flatten intervals into (position, ±1) events.
- Sort and sweep, accumulating the running count.
- Read the answer where activity peaks or boundaries break.
Greedy & Intervals
Deadline & Sequencing Greedy
Process jobs by profit; slot each into the latest free time before its deadline.
a.k.a. job scheduling, early deadline
Applies to
Maximising profit under deadlines
- Sort jobs by decreasing profit.
- For each job, find the latest free slot at or before its deadline.
- Fill that slot with the job.
Dynamic Programming (1D)
Dynamic Programming
Solve each state once, store the result, and build bigger answers from smaller ones.
a.k.a. dp, memoization, overlapping subproblems
Applies to
Optimal substructure over overlapping subproblems
- Define state clearly: what changes as you recurse.
- Write the recurrence between states.
- Pick an iteration order or use memoised recursion.
Dynamic Programming (1D)
Kadane / Max Subarray
The best subarray ending here is the current element or it plus the best ending before.
a.k.a. max subarray, running best
Applies to
Best contiguous sum ending at each position
- Track bestEnding and bestGlobal.
- bestEnding = max(x, bestEnding + x).
- Answer is the max of bestEnding over all positions.
Dynamic Programming (1D)
Fibonacci & Step-Climbing
Ways to reach state i are the ways to reach its predecessor states summed.
a.k.a. staircase, climb stairs
Applies to
Linear recurrences over step-by-step paths
- Identify a small, fixed recurrence between steps.
- Solve bottom-up iterating over positions.
- Keep only the last two or k values to save memory.
Dynamic Programming (1D)
Unbounded Coin Combinations
For each amount, best = 1 + best[amount − coin] over every coin.
a.k.a. coin change, unbounded dp
Applies to
Counting/optimising with reusable items
- Start dp[0]=0, the rest at infinity.
- For each amount, relax against every coin.
- Constants like 2× amount loops are fine at these bounds.
Dynamic Programming (1D)
Adjacent-Conflict DP
At each item choose skip (keep previous best) or take (its value + best two before).
a.k.a. house robber, no two adjacent
Applies to
Selecting non-adjacent items for max value
- dp[i] = max(dp[i−1], nums[i] + dp[i−2]).
- Walk forward maintaining only the last two results.
- Rotate conveniently if the input is a circle.
Dynamic Programming (1D)
Word Break Segmentation
dp[i] says whether prefix i is segmentable; try each dictionary word after every true prefix.
a.k.a. sentence split, dictionary split
Applies to
Segmenting a string into dictionary words
- dp[0]=true for the empty prefix.
- For each true prefix, mark every prefix extended by a word.
- Answer is dp[n] at the full length.
Dynamic Programming (2D)
Grid Paths (Right / Down)
Ways to reach a cell are the sum of reaching it from above and the left.
a.k.a. unique paths, lattice paths
Applies to
Counting or weighting monotonic grid routes
- Seed the top row and left column with base values.
- Fill interior cells from their two incoming neighbours.
- Read the target cell's final value.
Dynamic Programming (2D)
0/1 Knapsack
For each item decide skip or take (value + best at remaining capacity).
a.k.a. bounded dp, capacity dp
Applies to
Choosing a subset under a capacity/weight budget
- dp over (item index, capacity).
- take = value[i] + dp[i−1][capacity − weight[i]] when it fits.
- Keep whichever side is larger; roll to one row for space.
Dynamic Programming (2D)
Edit Distance
dp[i][j] = cost to convert a[..i] to b[..j], combining match, insert, delete, replace.
a.k.a. levenshtein, min edits
Applies to
Minimum insert/delete/replace between two strings
- Initialise the empty-to-something rows.
- Four-way transition per cell: match, insert, delete, replace.
- dp[m][n] is the answer.
Dynamic Programming (2D)
Longest Common Subsequence
Equal chars extend the diagonal; otherwise the best of the two smaller prefixes wins.
a.k.a. lcs, common subsequence
Applies to
Shared ordered subsequences of two strings
- dp[i][j] over the two string prefixes.
- Match char → 1 + diagonal.
- Mismatch → max of the two neighbours.
Dynamic Programming (2D)
Palindromic Substring DP
A substring is palindromic if its ends match and its interior is palindromic.
a.k.a. palindrome table, expand dp
Applies to
Counting/longest palindromic substrings
- Length-1 and length-2 substrings are base cases.
- For each length, verify ends match plus interior palindrome.
- Expand outward or rely on the table for the answer.
Dynamic Programming (2D)
Partition DP (Matrix-Chain Style)
Try every split point; the optimal is the best split's left + right cost.
a.k.a. mcm, split dp
Applies to
Costs that depend on where you split a range
- dp over (start, end) ranges, shortest first.
- For each split inside the range, combine subcosts with the split cost.
- The full range's best is the answer.
Math & Bit Manipulation
Bit Manipulation Toolkit
A few primitives — XOR, masks, shifts — replace loops for parity and set membership.
a.k.a. bitwise, xor, masks
Applies to
XOR dancing, set/count bits, mask tricks
- Know x ^ x = 0 and x ^ 0 = x.
- Count set bits with x &= (x − 1) or a precomputed table.
- Extract the last set bit with x & −x.
Math & Bit Manipulation
Math Hashing & Modular Life
Compress keys via modular arithmetic and exploit divisibility symmetries.
a.k.a. mod, gdc, divisibility
Applies to
Arithmetic that folds into hashes or modular invariants
- Reduce everything modulo a power or prime when overflow looms.
- Detect pairs by residue: complements live in the same bucket.
- Verify with small examples before scaling up.
Math & Bit Manipulation
Power / Multiply Fast
Square-and-multiply halves the exponent each step: O(log n) multiplications.
a.k.a. modular exponentiation, fast pow
Applies to
Large powers, matrix exponents, modular inverses
- While exponent > 0, square the base and halve the exponent.
- When the bit is set, fold the base into the answer.
- Keep everything modulo to stay in range.
Math & Bit Manipulation
Digit Manipulation
Extract the last digit with %10, rebuild with ×10+digit.
a.k.a. reverse int, digit extract
Applies to
Reading and rebuilding number digits
- Loop while n is nonzero: digit = n % 10.
- Accumulate: result = result * 10 + digit.
- Watch overflow by checking before multiplying.
Math & Bit Manipulation
Primes & The Sieve
Cross out every multiple of each prime — O(n log log n) to the limit.
a.k.a. sieve of eratosthenes, prime counting
Applies to
Counting or listing primes below a bound
- Mark everything as prime.
- For each unmarked value, cross out its multiples.
- The unmarked survivors are the primes; count them.
Ready to get interview-ready?
Join ProgramAlpha free, take the diagnostic and start your first track today.