LeetCode Patterns: 20 Coding Interview Patterns with Python Templates
LeetCode Patterns teaches the 20 problem-solving patterns behind most LeetCode and coding interview questions, with a reusable Python template for each one. For every pattern you get the signals that tell you to use it, a tested template you can adapt in minutes, its time and space complexity, the pitfalls that cost people accepted solutions, and a short list of classic LeetCode problems to practise on. It is for anyone preparing for software engineering interviews who would rather learn 20 patterns than memorise 500 answers.
All templates live in templates/ as plain Python 3 files with no dependencies, and every one is exercised by the pytest suite in tests/ on small worked examples.
Last reviewed: December 2026
Table of contents
- How to use this repo
- Run the templates and tests
- Pattern picker: which pattern fits?
- The 20 patterns
- Two pointers
- Fast and slow pointers
- Sliding window
- Prefix sum
- Binary search
- Monotonic stack and deque
- Merge intervals
- Cyclic sort
- In-place linked list reversal
- Tree DFS
- Tree BFS
- Graph and grid traversal
- Topological sort
- Union-find
- Top K elements
- K-way merge
- Two heaps
- Backtracking
- Dynamic programming
- Trie
- Constraints tell you the complexity
- A 4-week study plan
- Python tricks that save time in interviews
- Easy-to-confuse patterns
- Best first problem for each pattern
- FAQ
- Where to go next
- Contributing
- License
- More free resources
How to use this repo
- Read one pattern at a time. Start with the recognition signals, then read the template slowly until you can explain why each line is there.
- Close the file and rewrite the template from memory. Then run the tests to check yourself (see below).
- Solve the linked problems on LeetCode without looking. Before typing any code, say out loud which pattern applies and why. That habit is the actual interview skill.
- Come back after a few days and redo one problem per pattern. Spaced repetition beats volume.
Problem links point to the problem pages on leetcode.com. Every linked number, title and URL was checked against LeetCode, and all of them are free problems. A few classic pattern problems are premium-only on LeetCode; those are described in the text but not linked.
Run the templates and tests
git clone https://github.com/Ralpberry-Labs/leetcode-patterns.git
cd leetcode-patterns
python3 -m venv .venv && source .venv/bin/activate
pip install pytest
pytest # all patterns
pytest -k sliding # just one pattern
Try a template in the REPL from the repo root:
>>> from templates.sliding_window import longest_unique_substring
>>> longest_unique_substring("abcabcbb")
3
>>> from templates.structures import build_tree
>>> from templates.tree_bfs import level_order
>>> level_order(build_tree([3, 9, 20, None, None, 15, 7]))
[[3], [9, 20], [15, 7]]
templates/structures.py provides ListNode, TreeNode, and helpers that build them from LeetCode-style lists, so you can test linked list and tree code locally.
Pattern picker: which pattern fits?
Read the problem, then walk down this table and stop at the first row that matches.
| If the problem says or implies… | Try |
|---|---|
| Sorted array, find a pair/triplet, or compare both ends | Two pointers |
| Linked list cycle, middle of list, “repeating sequence” | Fast and slow pointers |
| Longest/shortest contiguous subarray or substring with a condition | Sliding window |
| Sum of a subarray or range, many range queries, “subarray sums to k” | Prefix sum |
| Sorted input, or “minimum X such that … is possible” | Binary search |
| Next greater/smaller element, spans, histograms | Monotonic stack |
| Ranges, meetings, bookings, overlapping intervals | Merge intervals |
| Numbers in range 1..n, find missing/duplicate in O(1) space | Cyclic sort |
| Reverse a linked list or part of it, in place | Linked list reversal |
| Tree paths, heights, subtree properties | Tree DFS |
| Tree levels, “closest to root”, left/right view | Tree BFS |
| Grid of cells, islands, spreading, shortest steps | Graph traversal |
| Prerequisites, dependencies, build order | Topological sort |
| Groups, connected components, redundant connection | Union-find |
| K largest/smallest/most frequent | Top K |
| Merge K sorted lists or arrays | K-way merge |
| Running median, balance two halves | Two heaps |
| All combinations, permutations, subsets, boards | Backtracking |
| Count ways, min/max cost, “can you reach”, overlapping subproblems | Dynamic programming |
| Prefix queries over a word list, wildcard word search | Trie |
Two extra questions that rescue many interviews:
- Can I sort the input? Sorting (O(n log n)) often unlocks two pointers, binary search, or a greedy interval sweep.
- Can a hash map remove the inner loop? Turning “for each pair” into “have I seen the complement?” is the most common O(n²) to O(n) improvement.
The 20 patterns
1. Two pointers
File: templates/two_pointers.py
Recognition signals
- The array is sorted, or sorting it does not lose information you need.
- You are looking for a pair or triplet with a target sum, or comparing elements from both ends.
- You must filter or compact an array in place with O(1) extra space.
Template: opposite ends
def pair_with_target_sum(nums: list[int], target: int) -> tuple[int, int] | None:
"""Opposite-ends template on a SORTED array: indices of a pair summing to target."""
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return left, right
if total < target:
left += 1 # need a bigger sum
else:
right -= 1 # need a smaller sum
return None
Template: same direction (reader and writer)
def remove_duplicates(nums: list[int]) -> int:
"""Same-direction (reader/writer) template: dedupe a sorted list in place.
Returns k; nums[:k] holds the unique values.
"""
write = 0
for read in range(len(nums)):
if read == 0 or nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return write
Complexity: O(n) time after sorting (O(n log n) if you sort), O(1) extra space. 3Sum is O(n²): one loop plus a two-pointer scan.
Pitfalls
- Duplicates: in 3Sum, skip equal anchors and equal values after a match, or you will output repeated triplets.
- Moving the wrong pointer. Ask “does moving this pointer make the sum bigger or smaller?” before writing the branch.
- On unsorted input where you must return original indices (Two Sum), use a hash map instead of sorting.
Example problems
- 167. Two Sum II - Input Array Is Sorted
- 15. 3Sum
- 11. Container With Most Water
- 125. Valid Palindrome
- 26. Remove Duplicates from Sorted Array
- 42. Trapping Rain Water
2. Fast and slow pointers
File: templates/fast_slow_pointers.py
Recognition signals
- A linked list that might loop, or you need its middle without knowing its length.
- A sequence defined by “next = f(current)” that either ends or repeats (happy number).
- Values in 1..n stored in n + 1 slots: indices form an implicit linked list with a cycle.
Template
def cycle_start(head: ListNode | None) -> ListNode | None:
"""Return the node where the cycle begins, or None.
After the meeting point, a pointer from the head and a pointer from the
meeting point, both moving one step, meet at the cycle entrance.
"""
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next # type: ignore[union-attr]
fast = fast.next.next
if slow is fast:
finder = head
while finder is not slow:
finder = finder.next # type: ignore[union-attr]
slow = slow.next # type: ignore[union-attr]
return finder
return None
Complexity: O(n) time, O(1) space.
Pitfalls
- Check
fast is not None and fast.next is not Nonebefore taking two steps. - Compare nodes with
is, not values: two different nodes can hold the same value. - For an even-length list this middle is the second middle; start
fast = head.nextif you need the first.
Example problems
- 141. Linked List Cycle
- 142. Linked List Cycle II
- 876. Middle of the Linked List
- 202. Happy Number
- 287. Find the Duplicate Number
- 234. Palindrome Linked List (find the middle, reverse the second half, compare)
3. Sliding window
File: templates/sliding_window.py
Recognition signals
- “Longest”, “shortest”, “number of” contiguous subarrays or substrings.
- A condition that is monotonic in window size: once a window is invalid, growing it keeps it invalid (or once valid, growing keeps it valid).
- Fixed size k windows: averages, anagrams, maximums of every k elements.
Template: longest valid window
def longest_unique_substring(s: str) -> int:
"""Variable window, 'longest valid' flavour: shrink while invalid."""
last_seen: dict[str, int] = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the previous copy
last_seen[ch] = right
best = max(best, right - left + 1)
return best
Template: shortest valid window
def min_subarray_len(target: int, nums: list[int]) -> int:
"""Variable window, 'shortest valid' flavour: shrink while still valid.
Requires non-negative numbers (so growing never lowers the sum).
"""
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else int(best)
Complexity: O(n) time, since each index enters and leaves the window once. Space is O(size of the alphabet or the counter).
Pitfalls
- Sliding window needs monotonicity. With negative numbers, “sum at least k” is not monotonic; use prefix sums plus a monotonic deque or a hash map instead.
- Update the answer in the right place: after shrinking for “longest valid”, while shrinking for “shortest valid”.
Counterequality ignores zero counts only from Python 3.10 on. Deleting keys whose count drops to zero (asfind_anagramsdoes) keeps the comparison correct on every version.
Example problems
- 3. Longest Substring Without Repeating Characters
- 209. Minimum Size Subarray Sum
- 76. Minimum Window Substring
- 438. Find All Anagrams in a String
- 424. Longest Repeating Character Replacement
- 567. Permutation in String
4. Prefix sum
File: templates/prefix_sum.py
Recognition signals
- Many queries for the sum of a range.
- “Number of subarrays whose sum equals k”, especially when values can be negative (which rules out a sliding window).
- “Equal number of X and Y” problems, which become “subarray sum equals 0” after mapping one of them to -1.
Template: count subarrays with sum k
def subarray_sum_count(nums: list[int], k: int) -> int:
"""Number of contiguous subarrays summing to k (works with negatives)."""
seen: dict[int, int] = defaultdict(int)
seen[0] = 1 # the empty prefix
running = count = 0
for x in nums:
running += x
count += seen[running - k]
seen[running] += 1
return count
For plain range queries, RangeSum in the same file stores prefix = [0, *accumulate(nums)] and answers each query as prefix[right + 1] - prefix[left].
Complexity: O(n) to build, O(1) per range query; the hash map variant is O(n) time and O(n) space.
Pitfalls
- Forgetting
seen[0] = 1, which counts subarrays that start at index 0. - Updating the map before counting, which lets a subarray of length zero count when k = 0.
- For “longest subarray” variants, store the first index where each prefix appears, not the latest.
Example problems
- 303. Range Sum Query - Immutable
- 560. Subarray Sum Equals K
- 525. Contiguous Array
- 238. Product of Array Except Self
- 304. Range Sum Query 2D - Immutable
5. Binary search
File: templates/binary_search.py
Recognition signals
- Sorted input, or input sorted in pieces (rotated arrays).
- O(log n) is required, or n is up to 10⁹ so you cannot scan.
- “Find the minimum speed/capacity/size such that the task is possible.” If a value works, every bigger value works too. That is binary search on the answer.
Template: first value where a monotonic predicate becomes true
def first_true(lo: int, hi: int, predicate: Callable[[int], bool]) -> int:
"""Smallest x in [lo, hi] with predicate(x) True; hi + 1 if none."""
hi += 1 # search the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if predicate(mid):
hi = mid
else:
lo = mid + 1
return lo
Template: binary search on the answer
def min_eating_speed(piles: list[int], hours: int) -> int:
"""Binary search on the answer (Koko eating bananas)."""
return first_true(1, max(piles), lambda k: sum(-(-p // k) for p in piles) <= hours)
Complexity: O(log n) predicate calls. On the answer: O(log(range) × cost of predicate).
Pitfalls
- Mixing closed
[lo, hi]and half-open[lo, hi)conventions. Pick one and stick with it; this repo uses half-open infirst_true. - Infinite loops from
lo = midwithmid = (lo + hi) // 2. Always make progress:lo = mid + 1orhi = mid. - Choosing bounds that do not contain the answer, such as starting the ship capacity at 1 instead of
max(weights).
Example problems
- 35. Search Insert Position
- 34. Find First and Last Position of Element in Sorted Array
- 33. Search in Rotated Sorted Array
- 153. Find Minimum in Rotated Sorted Array
- 875. Koko Eating Bananas
- 1011. Capacity To Ship Packages Within D Days
6. Monotonic stack and deque
File: templates/monotonic_stack.py
Recognition signals
- “Next greater element”, “next smaller element”, “how many days until warmer”.
- Each element needs to know the nearest element to its left or right that is bigger or smaller.
- Largest rectangle problems, stock spans, and “maximum of every window” (monotonic deque).
Template: next greater element
def next_greater(nums: list[int]) -> list[int]:
"""For each element, the next greater value to its right, or -1."""
result = [-1] * len(nums)
stack: list[int] = [] # indices with decreasing values
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
result[stack.pop()] = x
stack.append(i)
return result
The same file has max_sliding_window, the deque version: indices are kept with decreasing values, the front is the window maximum, and it is popped once it slides out of the window.
Complexity: O(n) time because every index is pushed and popped at most once; O(n) space.
Pitfalls
- Store indices, not values, whenever you need distances or widths.
- Decide
<vs<=deliberately: it controls how equal values are handled. - Remember the leftovers: elements still on the stack at the end have no next greater element. A sentinel (like the trailing 0 in
largest_rectangle) flushes them.
Example problems
- 496. Next Greater Element I
- 739. Daily Temperatures
- 84. Largest Rectangle in Histogram
- 239. Sliding Window Maximum
- 901. Online Stock Span
7. Merge intervals
File: templates/intervals.py
Recognition signals
- Input is a list of
[start, end]pairs: meetings, bookings, ranges, balloons. - Questions about overlaps, gaps, merging, or the maximum number of simultaneous events.
Template: merge overlapping intervals
def merge(intervals: list[list[int]]) -> list[list[int]]:
merged: list[list[int]] = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
Template: greedy by earliest end
def erase_overlap_intervals(intervals: list[list[int]]) -> int:
"""Fewest removals so the rest do not overlap: greedily keep earliest end."""
removed = 0
prev_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= prev_end:
prev_end = end
else:
removed += 1
return removed
The same file has min_rooms, a min-heap of end times that answers “how many meeting rooms do we need?” (the classic Meeting Rooms II question, which is premium on LeetCode).
Complexity: O(n log n) for the sort, then O(n) for the sweep.
Pitfalls
- Sort by start for merging, by end for “keep the most non-overlapping intervals”.
- Read the problem’s definition of touching: is
[1, 2]overlapping[2, 3]? Merge Intervals says yes; Non-overlapping Intervals says no. - Do not mutate the caller’s input list in place unless the problem allows it.
Example problems
- 56. Merge Intervals
- 57. Insert Interval
- 435. Non-overlapping Intervals
- 452. Minimum Number of Arrows to Burst Balloons
- 986. Interval List Intersections
8. Cyclic sort
File: templates/cyclic_sort.py
Recognition signals
- The array contains numbers in a known range such as 1..n or 0..n.
- You must find missing numbers, duplicates, or the first missing positive.
- O(n) time and O(1) extra space are required, which rules out sorting and hash sets.
Template
def cyclic_sort(nums: list[int]) -> list[int]:
"""Place each value v (in 1..n) at index v - 1, in place."""
i = 0
while i < len(nums):
home = nums[i] - 1
if 0 <= home < len(nums) and nums[i] != nums[home]:
nums[i], nums[home] = nums[home], nums[i]
else:
i += 1
return nums
def first_missing_positive(nums: list[int]) -> int:
"""Smallest positive integer not in nums (ignores values outside 1..n)."""
cyclic_sort(nums)
for i, v in enumerate(nums):
if v != i + 1:
return i + 1
return len(nums) + 1
Complexity: O(n) time (each swap puts at least one value in its final home), O(1) extra space.
Pitfalls
- Compare
nums[i] != nums[home], noti != home; otherwise duplicates cause an infinite loop. - Only increment
iwhen no swap happened. - Skip values outside the range (zero, negatives, values greater than n).
Example problems
- 268. Missing Number
- 448. Find All Numbers Disappeared in an Array
- 442. Find All Duplicates in an Array
- 645. Set Mismatch
- 41. First Missing Positive
9. In-place linked list reversal
File: templates/linked_list_reversal.py
Recognition signals
- Reverse a whole list, a sub-range, or every block of k nodes.
- Palindrome checks or reordering where O(1) extra space is required.
Template: reverse a list
def reverse_list(head: ListNode | None) -> ListNode | None:
prev: ListNode | None = None
cur = head
while cur is not None:
nxt = cur.next
cur.next = prev
prev, cur = cur, nxt
return prev
reverse_k_group in the same file applies this loop to each full block of k nodes, reconnecting each reversed block to the previous one through a dummy head; reverse_between reverses a sub-range by repeatedly moving the next node to the front of the range.
Complexity: O(n) time, O(1) extra space.
Pitfalls
- Save
cur.nextbefore overwriting it. - Use a dummy node whenever the head might change; it removes a whole class of edge cases.
- Draw the pointers on paper for a 3-node example before coding. Every off-by-one in this pattern shows up there.
Example problems
- 206. Reverse Linked List
- 92. Reverse Linked List II
- 25. Reverse Nodes in k-Group
- 24. Swap Nodes in Pairs
10. Tree DFS
File: templates/tree_dfs.py
Recognition signals
- Anything about root-to-leaf paths, heights, depths, or whether a subtree satisfies a property.
- The answer for a node can be built from the answers of its children (post-order), or depends on information from its ancestors (pre-order).
Template: post-order, combine children’s answers
def diameter(root: TreeNode | None) -> int:
"""Post-order: each call returns its height and updates a global best."""
best = 0
def height(node: TreeNode | None) -> int:
nonlocal best
if node is None:
return 0
left, right = height(node.left), height(node.right)
best = max(best, left + right) # edges on the path through `node`
return 1 + max(left, right)
height(root)
return best
The pre-order flavour passes information down instead: is_valid_bst hands each child the (low, high) range its value must fall in, and has_path_sum hands down the remaining sum.
Complexity: O(n) time, O(h) space for the recursion, where h is the tree height (O(n) for a skewed tree).
Pitfalls
- Ask “what does my function return to its parent?” before writing it. Mixing “what I return” with “the global answer” is the classic bug in diameter and max path sum problems.
- Validating a BST by only comparing a node with its direct children is wrong; pass the allowed range down.
- Python’s default recursion limit is about 1000 frames; deep skewed trees may need an explicit stack.
Example problems
- 104. Maximum Depth of Binary Tree
- 112. Path Sum
- 113. Path Sum II
- 543. Diameter of Binary Tree
- 236. Lowest Common Ancestor of a Binary Tree
- 98. Validate Binary Search Tree
11. Tree BFS
File: templates/tree_bfs.py
Recognition signals
- “Level”, “row”, “depth by depth”, “zigzag”, “right side view”.
- The answer is the shallowest node satisfying something (minimum depth), so you want to stop early.
Template
def level_order(root: TreeNode | None) -> list[list[int]]:
if root is None:
return []
levels: list[list[int]] = []
queue = deque([root])
while queue:
level: list[int] = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
Complexity: O(n) time, O(w) space where w is the maximum width of the tree.
Pitfalls
- Snapshot
len(queue)at the start of each level; the queue grows while you process it. - Use
collections.deque;list.pop(0)is O(n). - Minimum depth is measured to a leaf: a root with one child does not have depth 1.
Example problems
- 102. Binary Tree Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 199. Binary Tree Right Side View
- 111. Minimum Depth of Binary Tree
- 637. Average of Levels in Binary Tree
12. Graph and grid traversal
File: templates/graph_traversal.py
Recognition signals
- A 2-D grid where cells connect to their neighbours: islands, regions, mazes.
- “Minimum number of steps/minutes” in an unweighted graph: BFS.
- Several starting points spreading at the same time (rotting oranges, distance to nearest X): multi-source BFS.
Template: flood fill (count connected regions)
def num_islands(grid: list[list[str]]) -> int:
"""Count connected groups of '1' cells (iterative DFS flood fill)."""
rows, cols = len(grid), len(grid[0]) if grid else 0
seen: set[tuple[int, int]] = set()
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != "1" or (r, c) in seen:
continue
islands += 1
stack = [(r, c)]
seen.add((r, c))
while stack:
cr, cc = stack.pop()
for dr, dc in DIRECTIONS:
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1" and (nr, nc) not in seen:
seen.add((nr, nc))
stack.append((nr, nc))
return islands
For spreading processes, oranges_rotting in the same file seeds the queue with every rotten cell, then processes the queue one level (one minute) at a time, exactly like tree BFS.
Complexity: O(rows × cols) time and space for grids; O(V + E) for general graphs.
Pitfalls
- Mark a cell visited when you push it, not when you pop it, or it gets queued many times.
- Bounds checks first, then the cell value, to avoid index errors.
- Recursive DFS on a 1000 × 1000 grid will exceed Python’s recursion limit; use an explicit stack or BFS.
Example problems
- 200. Number of Islands
- 695. Max Area of Island
- 994. Rotting Oranges
- 1091. Shortest Path in Binary Matrix
- 133. Clone Graph
- 417. Pacific Atlantic Water Flow
13. Topological sort
File: templates/topological_sort.py
Recognition signals
- Tasks with prerequisites, build systems, package install order, course schedules.
- “Is it possible to finish all tasks?” (equivalent to “is the directed graph acyclic?”).
Template: Kahn’s algorithm
def find_order(num_courses: int, prerequisites: list[list[int]]) -> list[int]:
"""A valid course order, or [] if impossible. Pair [a, b] means b before a."""
graph: list[list[int]] = [[] for _ in range(num_courses)]
indegree = [0] * num_courses
for course, before in prerequisites:
graph[before].append(course)
indegree[course] += 1
queue = deque(i for i in range(num_courses) if indegree[i] == 0)
order: list[int] = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph[node]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return order if len(order) == num_courses else []
Complexity: O(V + E) time and space.
Pitfalls
- Get the edge direction right. In Course Schedule,
[a, b]means b must come before a, so the edge is b → a. - Nodes with no edges at all still belong in the order; initialise in-degree for every node.
- If the processed count is less than the number of nodes, there is a cycle. Do not return a partial order.
Example problems
- 207. Course Schedule
- 210. Course Schedule II
- 310. Minimum Height Trees (leaf peeling, a close cousin of Kahn’s algorithm)
14. Union-find
File: templates/union_find.py
Recognition signals
- “How many groups/components/provinces?”
- Edges or equivalences arrive one at a time and you ask about connectivity after each.
- “Which edge creates a cycle?” in an undirected graph.
Template
class UnionFind:
def __init__(self, n: int) -> None:
self.parent = list(range(n))
self.size = [1] * n
self.components = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.components -= 1
return True
Complexity: Effectively O(1) amortised per operation (inverse Ackermann) with path compression and union by size; O(n) space.
Pitfalls
- Always compare roots (
find(a) == find(b)), never parents. - Problems with 1-based node labels need an array of size n + 1.
- Union-find cannot cheaply remove edges. If edges disappear, process them in reverse or use another approach.
Example problems
- 547. Number of Provinces
- 684. Redundant Connection
- 990. Satisfiability of Equality Equations
- 721. Accounts Merge
15. Top K elements
File: templates/top_k_heap.py
Recognition signals
- “K largest”, “K smallest”, “K most frequent”, “K closest”, “K-th largest”.
- A stream where you keep only the best K seen so far.
Template: keep a min-heap of size k
def kth_largest(nums: list[int], k: int) -> int:
heap: list[int] = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return heap[0]
Template: let heapq do it
def top_k_frequent(nums: list[int], k: int) -> list[int]:
"""The k most frequent values, most frequent first."""
counts = Counter(nums)
return heapq.nlargest(k, counts, key=counts.__getitem__)
Complexity: O(n log k) time, O(k) space. Quickselect gets O(n) average for the K-th element when you do not need a stream.
Pitfalls
- For the K largest, use a min-heap (and vice versa). The root is the weakest member, the one to evict.
- Python’s
heapqis a min-heap only; push negated numbers (or tuples with negated keys) for a max-heap. - When heap entries are tuples, add a tie-breaker so Python never compares uncomparable objects.
Example problems
- 215. Kth Largest Element in an Array
- 347. Top K Frequent Elements
- 973. K Closest Points to Origin
- 703. Kth Largest Element in a Stream
- 1046. Last Stone Weight
16. K-way merge
File: templates/k_way_merge.py
Recognition signals
- K sorted lists, arrays, or matrix rows that must be combined or searched in order.
- “Smallest range covering one element from each list”, “K-th smallest across sorted inputs”.
Template
def merge_k_linked_lists(lists: list[ListNode | None]) -> ListNode | None:
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
heapq.heapify(heap)
dummy = tail = ListNode()
while heap:
_, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
Complexity: O(N log k) time for N total elements and k lists; O(k) heap space.
Pitfalls
- Push
(value, list_index, node)so equal values never fall through to comparingListNodeobjects (Python raisesTypeError). - Skip empty lists when building the initial heap.
- For a quick merge of plain Python iterables,
heapq.merge(*lists)already does this lazily.
Example problems
- 23. Merge k Sorted Lists
- 378. Kth Smallest Element in a Sorted Matrix
- 632. Smallest Range Covering Elements from K Lists
- 373. Find K Pairs with Smallest Sums
17. Two heaps
File: templates/two_heaps.py
Recognition signals
- A running median, or any statistic that splits the data into a lower and upper half.
- Choosing the best option among those currently “unlocked” (IPO: projects you can afford, ranked by profit).
Template: running median
class MedianFinder:
def __init__(self) -> None:
self.small: list[int] = [] # max-heap via negatives
self.large: list[int] = [] # min-heap
def add_num(self, num: int) -> None:
heapq.heappush(self.small, -num)
# Move the largest of the small half across so every small <= every large.
heapq.heappush(self.large, -heapq.heappop(self.small))
if len(self.large) > len(self.small):
heapq.heappush(self.small, -heapq.heappop(self.large))
def find_median(self) -> float:
if len(self.small) > len(self.large):
return float(-self.small[0])
return (-self.small[0] + self.large[0]) / 2
Complexity: O(log n) per insertion, O(1) per median query, O(n) space.
Pitfalls
- Keep the invariant every value in
small≤ every value inlarge, not just balanced sizes. Pushing through the other heap (as above) enforces both. - Decide which heap holds the extra element for odd counts, and read the median from it consistently.
- Sliding Window Median also needs deletion; use lazy deletion with a “to remove” counter.
Example problems
18. Backtracking
File: templates/backtracking.py
Recognition signals
- “Return all combinations / permutations / subsets / partitions / board placements.”
- Constraints are small (n ≤ 10 to 20), a hint that exponential search is expected.
- A decision is made step by step and some partial choices can be rejected early.
Template: choose, explore, un-choose
def subsets(nums: list[int]) -> list[list[int]]:
out: list[list[int]] = []
path: list[int] = []
def backtrack(start: int) -> None:
out.append(path.copy()) # every node of the tree is a subset
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return out
combination_sum in the same file sorts the candidates first so it can break as soon as a candidate exceeds the remaining target, and recurses with the same start index because each number may be reused.
Complexity: Exponential: O(2ⁿ × n) for subsets, O(n! × n) for permutations. Pruning changes the constant, not the class.
Pitfalls
- Append a copy (
path.copy()), notpathitself, or every stored answer ends up empty. - Duplicates in the input: sort first, then skip
nums[i] == nums[i - 1]wheni > start. - Undo every change you made before returning (including marks on a grid).
Example problems
- 78. Subsets
- 46. Permutations
- 39. Combination Sum
- 22. Generate Parentheses
- 51. N-Queens
- 79. Word Search
19. Dynamic programming
File: templates/dynamic_programming.py
Recognition signals
- “Number of ways”, “minimum cost”, “maximum profit”, “is it possible”, over sequences or grids.
- A brute-force recursion would solve the same subproblem many times.
- Choices at each step (take or skip, which coin, which move) with an optimal answer built from smaller answers.
The five-step recipe
- State: what does
dp[i](ordp[i][j]) mean, in one sentence? - Transition: how is a state computed from smaller states?
- Base cases: the smallest states you know directly.
- Order: fill states so dependencies are ready (usually increasing i).
- Answer and memory: which state is the answer, and can you keep only one or two rows?
Template: 1-D DP with two variables
def rob(nums: list[int]) -> int:
"""House robber: best = max(skip this house, take it + best two back)."""
prev2 = prev1 = 0
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1
Template: unbounded choices (coin change)
def coin_change(coins: list[int], amount: int) -> int:
"""Unbounded knapsack style: fewest coins for each amount, -1 if impossible."""
INF = amount + 1
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
dp[a] = min(dp[a], dp[a - c] + 1)
return dp[amount] if dp[amount] != INF else -1
Two-string problems use a 2-D table: dp[i][j] is the answer for a[:i] and b[:j]. longest_common_subsequence and min_distance in the same file show it, kept to a single row to save memory.
Complexity: number of states × work per state. Coin change is O(amount × coins); LCS is O(m × n) time and O(n) space here.
Pitfalls
- Fuzzy state definitions. If you cannot say what
dp[i]means in words, the transition will be wrong. - Loop direction in knapsack problems: iterate capacity downwards for 0/1 items (
can_partition), upwards for unlimited items (coin_change). - Starting from a top-down memoised recursion (
functools.cache) is fine in interviews; convert to bottom-up only if asked or if recursion depth is a problem.
Example problems
- 70. Climbing Stairs
- 198. House Robber
- 322. Coin Change
- 300. Longest Increasing Subsequence
- 1143. Longest Common Subsequence
- 72. Edit Distance
More DP in the same file: unique_paths, can_partition (0/1 subset sum), word_break and min_distance.
20. Trie
File: templates/trie.py
Recognition signals
- Many words, and questions about prefixes: “starts with”, autocomplete, shortest root.
- Wildcard matching against a dictionary.
- Searching a grid for many words at once (one DFS walking the grid and the trie together).
Template
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.word = word
def _walk(self, prefix: str) -> TrieNode | None:
node: TrieNode | None = self.root
for ch in prefix:
node = node.children.get(ch) # type: ignore[union-attr]
if node is None:
return None
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.word is not None
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not None
def search_wildcard(self, pattern: str) -> bool:
"""'.' matches any single letter (add-and-search-words)."""
def dfs(node: TrieNode, i: int) -> bool:
if i == len(pattern):
return node.word is not None
ch = pattern[i]
if ch == ".":
return any(dfs(child, i + 1) for child in node.children.values())
child = node.children.get(ch)
return child is not None and dfs(child, i + 1)
return dfs(self.root, 0)
Complexity: O(L) per insert or lookup for a word of length L; space is O(total characters inserted).
Pitfalls
- A prefix being present is not the same as a word being present; keep an end-of-word marker.
- Storing the whole word at its end node (as above) avoids rebuilding strings during DFS.
- In Word Search II, remove found words (or prune empty nodes) to avoid duplicate results and wasted work.
Example problems
- 208. Implement Trie (Prefix Tree)
- 211. Design Add and Search Words Data Structure
- 648. Replace Words
- 212. Word Search II
Constraints tell you the complexity
Typical judges allow roughly 10⁷ to 10⁸ simple operations per second, and Python is at the slow end. Read the input limits first: they tell you which complexity the intended solution has.
| Largest n | Target complexity | Patterns that fit |
|---|---|---|
| n ≤ 10 to 12 | O(n!) | Permutation backtracking |
| n ≤ 20 to 25 | O(2ⁿ) | Subset backtracking, bitmask DP |
| n ≤ 500 | O(n³) | Interval DP, Floyd-Warshall |
| n ≤ 5,000 | O(n²) | 2-D DP, nested loops with pruning |
| n ≤ 10⁵ to 10⁶ | O(n log n) or O(n) | Sorting, heaps, binary search, two pointers, sliding window, prefix sums |
| n up to 10⁹ or more | O(log n) or O(1) | Binary search on the answer, maths |
A 4-week study plan
About one hour a day. Each day: re-type the template from memory, run pytest -k <pattern>, then solve two of the linked problems.
| Week | Days 1-2 | Days 3-4 | Days 5-6 | Day 7 |
|---|---|---|---|---|
| 1 | Two pointers | Sliding window | Prefix sum | Review: redo one problem per pattern |
| 2 | Binary search | Monotonic stack | Intervals, cyclic sort | Review |
| 3 | Linked list reversal, fast/slow | Tree DFS, tree BFS | Graph traversal, topological sort | Review |
| 4 | Union-find, top K, k-way merge | Two heaps, trie | Backtracking, dynamic programming | Mock interview: random problems, timed |
Keep a one-line log per problem: the pattern, the key insight, and the mistake you made. Reviewing that log before an interview is worth more than solving new problems the night before.
Python tricks that save time in interviews
from collections import Counter, defaultdict, deque
import heapq
from bisect import bisect_left, bisect_right
from functools import cache
counts = Counter("mississippi") # letter frequencies
counts.most_common(2) # [('i', 4), ('s', 4)]
graph = defaultdict(list) # adjacency list without key checks
graph["a"].append("b")
queue = deque([0]) # O(1) popleft for BFS
queue.popleft()
heap = []
heapq.heappush(heap, (-5, "max-heap via negation"))
heapq.nsmallest(2, [5, 1, 4, 2]) # [1, 2]
bisect_left([1, 3, 3, 7], 3) # 1, first index >= 3
bisect_right([1, 3, 3, 7], 3) # 3, first index > 3
@cache # instant memoisation for top-down DP
def ways(n: int) -> int:
return 1 if n <= 1 else ways(n - 1) + ways(n - 2)
grid = [[0] * 3 for _ in range(2)] # NOT [[0] * 3] * 2 (shared rows)
float("inf"), -float("inf") # sentinels for min/max
divmod(17, 5) # (3, 2)
-(-7 // 2) # 4, integer ceiling division
Easy-to-confuse patterns
Most wrong approaches in interviews come from picking a neighbouring pattern. These tables show how to tell them apart.
Two pointers vs sliding window vs prefix sum
| Question | Two pointers | Sliding window | Prefix sum + hash map |
|---|---|---|---|
| What moves? | Two independent indices, often from both ends | A contiguous window that grows right and shrinks left | Nothing; one pass with a running total |
| Needs sorted input? | Usually (pair sums) | No | No |
| Handles negative numbers? | Yes | Only if the window condition stays monotonic | Yes |
| Typical question | “Pair with sum X in a sorted array” | “Longest substring with at most K distinct characters” | “Count subarrays summing to K” |
| Best pick when | You compare elements at two positions | You need the best contiguous range under a monotonic rule | Values can be negative or you need exact-sum counts |
BFS vs DFS
| Question | BFS | DFS |
|---|---|---|
| Data structure | Queue (collections.deque) |
Stack or recursion |
| Finds fewest steps in an unweighted graph | Yes | No |
| Memory | Width of the graph or tree | Depth of the graph or tree |
| Natural for | Levels, shortest paths, spreading processes | Paths, subtrees, cycle detection, backtracking, topological order |
| Best pick when | The question says “minimum number of steps/moves/minutes” | You need every path, or the answer is built from subtrees |
Heap vs sort vs quickselect for “top K”
| Approach | Time | Space | Best pick when |
|---|---|---|---|
| Sort everything | O(n log n) | O(n) | n is small or you need all items in order anyway |
| Heap of size k | O(n log k) | O(k) | k is much smaller than n, or data arrives as a stream |
| Quickselect | O(n) average, O(n²) worst | O(1) extra in place | You need the K-th element once, not a stream |
| Bucket by frequency | O(n) | O(n) | “Top K frequent” where counts are bounded by n |
Union-find vs DFS/BFS for connectivity
| Question | Union-find | DFS / BFS |
|---|---|---|
| Edges arrive over time, queries in between | Natural fit | Must re-run the search |
| Need the actual path between nodes | No | Yes |
| Directed graphs | Not suitable | Yes |
| Code length in an interview | About 15 lines | About 10 lines |
| Best pick when | Dynamic connectivity, cycle detection while adding edges | A one-off count of components or any path question |
Greedy vs dynamic programming vs backtracking
| Question | Greedy | Dynamic programming | Backtracking |
|---|---|---|---|
| Returns | One optimal answer, if a local rule is provably safe | An optimal value or a count | Every valid configuration |
| Typical cost | O(n log n) | Polynomial (states × transitions) | Exponential |
| Risk | Wrong answer when the local choice is not safe | Too many states, memory limits | Time limit on large inputs |
| Example | Non-overlapping Intervals (keep earliest end) | Coin Change (fewest coins) | Combination Sum (list every combination) |
| Best pick when | You can prove an exchange argument | Subproblems overlap and you need a number | The question asks for all solutions, n is small |
Best first problem for each pattern
If you only have time for one problem per pattern, start with these. Each one isolates the core idea with as little extra logic as possible.
| Pattern | Start with | Why this one |
|---|---|---|
| Two pointers | 167. Two Sum II - Input Array Is Sorted | The opposite-ends template with nothing else on top |
| Fast and slow pointers | 141. Linked List Cycle | Shows why two speeds must meet inside a cycle |
| Sliding window | 3. Longest Substring Without Repeating Characters | The canonical “grow right, shrink left” window |
| Prefix sum | 560. Subarray Sum Equals K | Teaches the prefix + hash map trick that sliding windows cannot do |
| Binary search | 875. Koko Eating Bananas | Binary search on the answer, the most reusable form |
| Monotonic stack | 739. Daily Temperatures | Next-greater-element with distances, in its purest form |
| Merge intervals | 56. Merge Intervals | Sort then sweep, the base of every interval problem |
| Cyclic sort | 448. Find All Numbers Disappeared in an Array | Index-as-hash with no other tricks |
| Linked list reversal | 206. Reverse Linked List | The three-pointer loop every harder variant reuses |
| Tree DFS | 543. Diameter of Binary Tree | Separates “what I return” from “the global answer” |
| Tree BFS | 102. Binary Tree Level Order Traversal | The level-by-level queue loop |
| Graph traversal | 200. Number of Islands | Grid flood fill, the most common graph question |
| Topological sort | 207. Course Schedule | Kahn’s algorithm plus cycle detection |
| Union-find | 547. Number of Provinces | Counting components with the plain template |
| Top K elements | 215. Kth Largest Element in an Array | Size-k min-heap; also a good quickselect exercise |
| K-way merge | 23. Merge k Sorted Lists | The heap-of-heads template exactly |
| Two heaps | 295. Find Median from Data Stream | The balancing invariant without distractions |
| Backtracking | 78. Subsets | Choose, explore, un-choose at its simplest |
| Dynamic programming | 198. House Robber | A one-line transition that teaches state definition |
| Trie | 208. Implement Trie (Prefix Tree) | Builds the structure every other trie problem uses |
FAQ
How many LeetCode problems should I solve before an interview? There is no magic number. Solving two to five problems per pattern, and being able to explain why the pattern fits, prepares you better than a large count solved by memory. Track the patterns you get wrong and repeat those.
What are the most important LeetCode patterns? Judged by how often they appear in common interview lists: hash maps, two pointers, sliding window, binary search, tree DFS/BFS, graph BFS/DFS, heaps and dynamic programming. Union-find, tries, monotonic stacks and cyclic sort show up less often but are quick wins once learned.
How do I know which pattern to use? Read the constraints and the shape of the question first. Use the pattern picker and the constraints table: “contiguous” suggests a window or prefix sum, “sorted” suggests two pointers or binary search, “all combinations” suggests backtracking, “minimum steps” suggests BFS.
Should I use Python for coding interviews?
Python is widely accepted and its short syntax plus collections, heapq and bisect save time. Use the language you are most fluent in; interviewers care more about clear reasoning and correct complexity than the language.
Is LeetCode Premium required? No. Every problem linked in this repo is free. Premium adds company tags and some extra problems (for example the Meeting Rooms series), but all 20 patterns can be learned with free problems.
What is the difference between a pattern and an algorithm? An algorithm is a specific procedure such as Dijkstra or merge sort. A pattern is a reusable way of approaching a family of problems, such as “keep a window and shrink it when invalid”. Patterns help you recognise which algorithm or data structure to reach for.
How do I get better at dynamic programming?
Write the state definition in words before any code, start from a brute-force recursion, add functools.cache, and only then convert to a bottom-up table. Practise the classic families in order: 1-D (house robber), knapsack (coin change, partition), two strings (LCS, edit distance), grids (unique paths) and intervals.
Why does my sliding window give wrong answers with negative numbers? A sliding window assumes that shrinking from the left always moves the window towards validity. Negative numbers break that, because removing a negative value increases the sum. Switch to prefix sums with a hash map.
My recursive solution hits a RecursionError. What now?
Python’s default recursion limit is about 1000 frames. Use an explicit stack or a queue for deep trees and large grids, or convert top-down DP to bottom-up. sys.setrecursionlimit helps for moderately deep inputs but is not a robust fix.
Should I memorise these templates?
Understand them well enough to rebuild them in a couple of minutes. The tests in this repo let you check a template you rewrote from memory: replace the function body, run pytest -k <pattern>, and see what breaks.
Where to go next
Every link below was checked when this page was last reviewed.
Question lists and study schedules
- Tech Interview Handbook: free guides on the whole interview process, from resumes to behavioural rounds.
- Grind 75: a curated interview question list with a study schedule.
- NeetCode roadmap: interview problems arranged as a topic graph, with video explanations.
Learn the algorithms underneath the patterns
- VisuAlgo: animations of sorting, heaps, graph traversal, shortest paths and more.
- MIT 6.006 Introduction to Algorithms (Spring 2020, MIT OpenCourseWare): a full university course with lectures and problem sets.
- Algorithms by Jeff Erickson: a free textbook; the recursion, backtracking and DP chapters pair well with patterns 18 and 19.
- CP-Algorithms: in-depth articles on graphs, strings, union-find and data structures.
Python references
collections,heapq,bisectandfunctools: the four modules used most in these templates.- TimeComplexity (Python wiki): what list, dict, set and deque operations cost, so your Big-O claims are right.
More practice beyond LeetCode
- CSES Problem Set: 400 classic problems sorted by topic, good for drilling one pattern at a time.
- USACO Guide: a structured path through the same patterns with harder follow-ups.
- Competitive Programmer’s Handbook (PDF): a free book that explains many of these techniques in more depth.
Contributing
Pull requests are welcome. Please keep entries accurate:
- Every template must have a test in
tests/with a small worked example, andpytestmust pass. - Only link LeetCode problems whose number, title and URL you have checked, and prefer free problems.
- Keep templates short and general; one clear version beats three clever ones.
- Fixes to explanations, pitfalls and complexity notes are as welcome as new code.
License
Code and text are released under the MIT License.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.