Python Patterns · Pattern finder
Read the signal, pick the pattern.
Describe your problem in two or three taps — the shape of the input, then what you're asked for — and the finder names the pattern that fits, why, and the near-misses to rule out.
Every signal at a glance
Rules of thumb
- Sorted input + a pair or target → try two pointers before a hash map.
- Contiguous run + non-negative values → sliding window; negatives → prefix sums with a hash map.
- Range totals on a fixed list → prefix sums; values that change → segment or Fenwick tree.
- "Next greater" or "first smaller" for each item → monotonic stack of indices.
- Unweighted fewest steps → BFS; non-negative weights → Dijkstra; negative edges → Bellman-Ford.
- Many starting points at once → put them all in one BFS queue at distance 0.
- Groups that merge as edges arrive → Union-Find; one fixed grid → flood fill.
- Minimise the maximum or maximise the minimum → binary search on the answer.
- Best choice reuses best answers to smaller inputs → write the state and recurrence, then DP.
- Top k of n with k much smaller than n → a size-k heap, not a full sort.
- Overlapping intervals → sort by end to keep the most, by start to merge, by event to count.
- Need every combination or ordering → backtracking; choose, recurse, then undo.
Is the data sorted, or does a yes/no answer flip once?5
Order is information: when the input is sorted, or a test is false and then true, you can discard half the work at every step.
Find a value, or its first or last position, in a sorted list
Decide up front whether hi is inclusive; most off-by-one bugs live there.
Sorted list, find a pair or triple that meets a target
01Two Pointers05HashMap / HashSet Lookups
Two pointers use O(1) space on sorted data; a hash map is the fallback when the input is unsorted.
"Smallest capacity that works" or "largest minimum gap" over a numeric range
Binary search the answer, not the array. It needs a feasible(x) check that flips exactly once.
Ordered tree: kth smallest, successor, or "is this a valid search tree?"
47BST Properties13DFS on Trees (Recursive)
An in-order walk of a BST visits the keys in sorted order. Check bounds, not just parent and child.
Merge many sorted lists, or always take the smallest head across K streams
30Merge K Sorted Lists / Arrays
Keep one head per list in a min-heap: O(N log K), not O(N log N).
Are you asked about a contiguous run?6
Subarrays and substrings are neighbours in a row, so you can often keep a running total instead of starting over at each index.
Longest or shortest run under a limit, with all values non-negative
Grow on the right, trim on the left. Each index enters and leaves the window once.
Count runs that sum to exactly k, and values can be negative
03Prefix Sum / Difference Array05HashMap / HashSet Lookups
Negatives break the window: shrinking no longer lowers the total. Store prefix totals in a hash map.
Many range-total questions on a list that never changes
03Prefix Sum / Difference Array
Build prefix once; each answer is prefix[hi + 1] − prefix[lo]. Use a difference array for range adds.
Range totals, minimums or maximums while values keep changing
32Segment Tree / Fenwick Tree41Binary Indexed Tree (BIT) Problems
One update makes prefix sums O(n) to rebuild. A segment tree answers and fixes in O(log n).
Best total of any contiguous run
04Kadane's Algorithm191D DP (Linear)
Kadane is 1D DP with one variable: extend the run or start fresh. Track min too for products.
Maximum or minimum of every window of size k
A heap leaves stale values behind; a monotonic deque drops them and reads the max in O(1).
Do you need "what have I seen?" in constant time?5
When a nested loop is only searching for a match, a hash map or set usually replaces the inner loop.
Pair that adds to a target in an unsorted list; duplicates; frequency counts
Check the map before you insert the current item, so an element never pairs with itself.
Values are exactly 1..n (or 0..n); find what is missing or repeated in O(1) space
42Cyclic Sort36Bit Manipulation
Swap each value to its home index. XOR also finds a single missing number.
Many lookups by prefix: autocomplete, "does any word start with…"
31Trie (Prefix Tree)05HashMap / HashSet Lookups
A hash map answers whole-word lookups. Reach for a trie once prefixes or wildcards matter.
Find a pattern inside text, or compare many substrings quickly
44String Manipulation Patterns
KMP or a rolling hash avoids re-scanning; expand around centres for palindromes.
Build a class with get/put in O(1) and an eviction rule
45Design Problems05HashMap / HashSet Lookups
Name each operation’s cost first, then pair structures: a map for lookup, a list or heap for order.
Does each item wait for the next bigger or smaller one?4
A stack that stays in sorted order lets each new value settle everything it beats in one pass.
For each item, the next greater (or smaller) item to its right
Store indices, not values, so you can measure distances when you pop.
Largest rectangle under bars, or in a 0/1 matrix row by row
39Monotonic Stack for Histogram Problems08Monotonic Stack
Histogram stack is the monotonic stack plus a width: close a bar when a shorter one arrives. Add a 0 sentinel.
Window max or min that slides by one each step
10Monotonic Queue / Deque08Monotonic Stack
Stack pops only from one end; the deque also drops the front as it leaves the window.
Matching brackets, nested expressions, or decoding "3[ab]"
09Valid Parentheses / Stack Matching
Push on open, pop and check on close. The stack must be empty at the end.
Is it a linked list?3
With no indexes to jump to, linked lists reward pointer tricks that use O(1) extra space.
Cycle detection, the middle node, or a repeating number sequence
06Fast & Slow Pointers (Floyd's)
Fast moves two, slow moves one. If they meet there is a cycle; when fast ends, slow is the middle.
Reverse the whole list, a section, or groups of k
Save next before you rewire. A dummy head saves special-casing the first node.
Palindrome check or reorder on a list in O(1) space
06Fast & Slow Pointers (Floyd's)07Linked List Reversal
Find the middle with fast and slow, reverse the second half, then walk both halves.
Is it a tree?3
Most tree questions are one recursive function: decide what each node returns to its parent.
Height, diameter, path sums, or lowest common ancestor
Post-order when a node needs its children’s answers; carry the best-so-far separately.
Anything "per level": averages, right-side view, minimum depth
14BFS on Trees / Graphs (Level Order)
Snapshot len(queue) at the start of each level so you know where it ends.
Rebuild a tree from traversal lists, or serialise and deserialise it
46Recursion & Tree Construction
Pre-order names the root; in-order splits left from right. Use a value→index map for O(n).
Is it a graph or a grid of connected cells?8
Ask whether you need reachability, groups, an order, or a distance, and whether edges carry weights.
Count islands or regions in a fixed grid; fill a region
15DFS on Graphs (Islands / Flood Fill)16Union-Find (Disjoint Set)
Flood fill is simplest when the grid is fixed. Mark a cell visited when you push it.
Edges arrive one at a time; "are these two connected yet?"
16Union-Find (Disjoint Set)15DFS on Graphs (Islands / Flood Fill)
Union-Find handles merges as they come; flood fill would redo the whole search each time.
Tasks with prerequisites; a build order; "can all be finished?"
Kahn’s algorithm: if fewer nodes come out than went in, there is a cycle.
Fewest steps, and every move costs the same
14BFS on Trees / Graphs (Level Order)18Dijkstra's Shortest Path
Plain BFS is already shortest when all weights are equal; Dijkstra adds a heap for nothing.
Distance from the nearest of many starts: spreading rot, nearest exit
48Multi-source BFS14BFS on Trees / Graphs (Level Order)
Put every source in the queue at distance 0. Running one BFS per source is far slower.
Cheapest path with non-negative edge weights
Skip a popped entry whose distance is stale. It is wrong once any edge is negative.
Some edges are negative, a hop limit, or all-pairs distances
49Bellman-Ford / Floyd-Warshall18Dijkstra's Shortest Path
Bellman-Ford relaxes every edge n − 1 times; a change on pass n means a negative cycle.
Connect every point at the lowest total cost
50Minimum Spanning Tree (Prim's / Kruskal's)16Union-Find (Disjoint Set)
That is a spanning tree, not a shortest path. Kruskal sorts edges and joins with Union-Find.
Are you choosing among overlapping options, with smaller versions of the same question?7
If the best answer reuses best answers to smaller inputs, write the state, the choice and the base case, then fill a table or memoise.
Answer at i depends on a few earlier answers: stairs, robbing houses, decoding
191D DP (Linear)37Memoization (Top-Down DP)
If only the last one or two values matter, keep two variables instead of a list.
The recursion is clear but repeats the same calls
37Memoization (Top-Down DP)191D DP (Linear)
Add @cache to the natural recursion. Switch to a table if the depth risks the recursion limit.
Pick items under a capacity or sum; can a subset reach a target?
21Knapsack Pattern (0/1 & Unbounded)191D DP (Linear)
0/1 loops capacity downward so each item is used once; unbounded loops upward.
Two sequences compared position by position: common subsequence, edit distance
23DP on Strings202D DP (Grid / Matrix)
dp[i][j] means "first i of one, first j of the other". DP on strings is 2D DP with letters as axes.
Walk a real grid moving right or down, with costs or obstacles
38Matrix / Grid DP202D DP (Grid / Matrix)
Grid DP: the table is the grid. Can you move up or left as well? Then it is a graph search.
Answer for a range [i, j] built from its splits: bursting, merging, palindromes
Fill by interval length, shortest first, so every split is ready before you need it.
Each day you are in one of a few modes: holding, sold, cooling down
Draw the states and arrows first; each arrow becomes one line of the update.
Must you list every option, or place things under rules?3
When the output is all the combinations, you cannot beat exponential time; backtracking keeps it tidy.
All subsets or combinations; choose or skip each item
25Subsets / Power Set36Bit Manipulation
Sort first and skip equal neighbours to avoid duplicates. A bitmask also lists subsets when n is small.
All orderings of the items
Choose an unused item, recurse, then unchoose. n! results, so only for small n.
Place items or trace a path on a board: word paths, queens, sudoku
27Backtracking on Grids15DFS on Graphs (Islands / Flood Fill)
Unlike flood fill, unmark a cell when you return, so other paths can use it.
Do you only need the top few, a median, or the extremes?4
A heap keeps the best candidates in order without sorting everything.
The k largest, most frequent or closest items
28Top K Elements43Divide and Conquer
A size-k heap is O(n log k) and works on a stream. Quickselect averages O(n) but needs the whole list.
Running median as numbers arrive
Max-heap for the lower half, min-heap for the upper; rebalance so sizes differ by at most one.
Split, solve both halves, combine: sorting, closest pair, kth element
The merge step is where the work hides. Write down its cost before you trust O(n log n).
For each item, count how many later items are smaller; count inversions
41Binary Indexed Tree (BIT) Problems43Divide and Conquer
Walk right to left and query a Fenwick tree of ranks. Merge sort can count inversions too.
Are there intervals, or a reach that grows?3
Sort by the right key and a safe local choice is often all you need.
Keep the most non-overlapping intervals, or merge the overlapping ones
To keep the most, sort by end time. To merge, sort by start.
Most intervals active at once; rooms or platforms needed
40Line Sweep Algorithm33Greedy Interval Scheduling
Line sweep: +1 at each start, −1 at each end. If an end and a start tie, apply the end first.
Can you reach the end, or in how few jumps; a fuel loop that must close
34Greedy Jumps / Range Expansion191D DP (Linear)
Track the farthest reach so far. DP also works, but it is O(n²) where greedy is O(n).
Is the trick in the numbers themselves?2
Some problems collapse once you spot a formula, a divisibility rule or a bit identity.
GCD, primes up to n, counting arrangements, answers "mod 10⁹+7"
Take the modulus after every multiply, not at the end. A sieve beats testing each number.
Every value appears twice except one; powers of two; flags packed in an int
36Bit Manipulation05HashMap / HashSet Lookups
x ^ x == 0, so XOR of all values leaves the odd one out in O(1) space.