24 Coding Interview Patterns, One Slide Each
1) Two Pointers
1. Two Pointers
Place one pointer at each end of a sorted array or string and move them toward each other, or move both in the same direction at different speeds.
Each step discards at least one element, so the scan is O(n).
Use when:
- Finding pairs in a sorted array, removing duplicates or merging
- Checking palindromes by comparing both ends
2) Prefix Sums
2. Prefix Sums
Precompute running totals so the sum of any range is the difference of two prefix values.
Answers each range query in O(1) after an O(n) setup.
Array
Prefix sums
Use when:
- Many queries asking for the sum of a range
- Replacing repeated O(n) summing with O(1) lookups
3) Sliding Window
3. Sliding Window
Grow a window by moving the right edge and shrink it from the left when a constraint breaks.
The window can have a fixed size or stretch and shrink as needed.
Fixed
Variable
Use when:
- Longest or shortest subarray or substring meeting a condition
- Fixed size windows over arrays or strings
4) Kadane's Algorithm
4. Kadane's Algorithm
Finds the largest sum of any contiguous subarray in O(n).
Keep a running sum and reset it to zero whenever it turns negative, since a negative prefix can only hurt.
Best sum = 6, from [3, -1, 4]
Use when:
- Maximum subarray sum, or its product variant
5) Counting Subarrays
5. Counting Subarrays
Combines prefix sums with a hash map. Count how often each prefix sum has appeared.
A subarray sums to k exactly when the current prefix minus k was seen before.
count, prefix, seen = 0, 0, {0: 1}
for x in nums:
prefix += x
count += seen.get(prefix - k, 0)
seen[prefix] = seen.get(prefix, 0) + 1Use when:
- How many subarrays sum to exactly k?
- How many subarrays have equal counts of two things?
6) Fast and Slow Pointers
6. Fast and Slow Pointers
Also known as Floyd's cycle detection. One pointer moves two steps for every one step of the other.
If there is a cycle, the fast pointer eventually catches the slow one.
slow on 2, fast on 4
Use when:
- Detecting a cycle in a linked list
- Finding the middle node or the start of a cycle
7) Depth First Search
7. Depth First Search
Explore one path as deeply as possible before backing up. Use recursion or an explicit stack.
Preorder: node, left, right. Inorder: left, node, right. Postorder: left, right, node.
Use when:
- Walking every path in a tree or graph
- Connected components, path existence and backtracking
8) Breadth First Search
8. Breadth First Search
Visit nodes one level at a time with a queue, so the first time you reach a node is along a shortest path.
Use when:
- Shortest path in an unweighted graph or grid
- Level by level processing of a tree
9) Matrix Traversal
9. Matrix Traversal
Treat every cell of a grid as a node with up to four neighbors, and run DFS or BFS over the cells you are allowed to enter.
Use when:
- Flood fill, counting islands and spreading processes
- Any grid where moves go up, down, left or right
10) Adjacency List BFS / DFS
10. Adjacency List BFS / DFS
Build a map from each vertex to its neighbors, then traverse it. Keep a visited set so cycles do not loop forever.
"A": ["B", "D"] "B": ["C"] "C": [] "D": ["C"]
Use when:
- Is there a path from A to B?
- Counting paths or components in a graph
11) Two Heaps
11. Two Heaps
Split the data into a lower half in a max heap and an upper half in a min heap, keeping their sizes within one.
The median sits on top of the two heaps.
[2, 3, 5, 7, 8, 9]
Max heap
Min heap
Median = (5 + 7) / 2 = 6
Use when:
- Running median of a stream
- Balancing a low side against a high side
12) Modified Binary Search
12. Modified Binary Search
Binary search over anything ordered: a rotated array, a matrix, or a range of possible answers.
while lo < hi:
mid = (lo + hi) // 2
if condition(mid): # does mid work?
hi = mid
else:
lo = mid + 1
return lo # first value that works💡 The input does not need to be an array. It only needs a condition that flips once.
Use when:
- Rotated arrays, peaks and boundaries
- Minimizing a speed, capacity or time
13) Topological Sort
13. Topological Sort
Order the vertices of a directed acyclic graph so every edge points forward. Repeatedly take a vertex with no remaining incoming edges.
If you run out of such vertices early, the graph has a cycle.
Use when:
- Scheduling tasks with dependencies
- "Can every course be finished?" and build order problems
14) Top K
14. Top K
Find the k largest, smallest or most frequent items with a heap that never grows past k.
Push each item and pop the top whenever the heap is too big.
Top 3
Use when:
- The k largest or k smallest items
- Usually paired with a min heap or max heap
15) Linked List Reversal
15. Linked List Reversal
Walk the list once and flip each next pointer to point backward. Keep track of the previous, current and next nodes.
Use when:
- Reversing all or part of a list in place
- Palindrome lists and reversing groups of k nodes
16) Permutations
16. Permutations
Build every ordering of the input. At each level, try every element that is not used yet.
Only complete paths, the leaves, are answers.
Use when:
- Generate every possible order or arrangement
- Order matters and nothing repeats
17) Combinations
17. Combinations
Choose k items out of n. Like subsets, each branch only uses items after the last choice, and a path stops at length k.
Every path of length k is an answer.
n = 3, k = 2: [1,2] [1,3] [2,3]
Use when:
- "Pick k items" where order does not matter
18) Tree Maze (Backtracking)
18. Tree Maze (Backtracking)
Search for a valid path from the root to a leaf. Step forward when a node is allowed, and back up the moment you hit a dead end.
Red nodes are walls. Green is the path found.
Use when:
- Does any valid path exist?
- Return the path, not just yes or no
19) Longest Common Subsequence
19. Longest Common Subsequence
A 2D dynamic programming table where cell (i, j) holds the LCS of the first i letters of one string and the first j letters of the other.
Use when:
- Comparing two sequences, such as edit distance or diff tools
20) Monotonic Stack
20. Monotonic Stack
A stack that stays sorted. Pop everything that breaks the order before pushing a new value.
Use when:
- Next or previous greater or smaller element
- Histogram and temperature span problems
21) Memoization
21. Memoization
Top down dynamic programming: write the recursive solution, then cache every answer so each subproblem is solved once.
from functools import cache
@cache
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)Use when:
- Recursion with overlapping subproblems
- Exponential brute force that repeats work
22) Tabulation
22. Tabulation
Bottom up dynamic programming. Fill a table from the base cases toward the final answer.
When each row only needs the previous one, keep two rows instead of the whole table.
Use when:
- Building answers from smaller answers
- The order to solve subproblems is clear
23) Multi-Source BFS
23. Multi-Source BFS
Start BFS from every source at once by putting all of them in the queue first. Each round spreads one step from all sources together.
Numbers show the round each cell is reached.
Use when:
- Several starting points spreading in parallel
- "Minimum time until everything is reached" problems
24) Merge Intervals
24. Merge Intervals
Sort intervals by start time, then walk through them, merging any interval that starts before the current one ends.
Use when:
- Merging, inserting or finding gaps between ranges
- "Can one person attend every meeting?"