Skip to the content.

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

  1. 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.
  2. Close the file and rewrite the template from memory. Then run the tests to check yourself (see below).
  3. 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.
  4. 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:

The 20 patterns

1. Two pointers

File: templates/two_pointers.py

Recognition signals

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

Example problems

2. Fast and slow pointers

File: templates/fast_slow_pointers.py

Recognition signals

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

Example problems

3. Sliding window

File: templates/sliding_window.py

Recognition signals

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

Example problems

4. Prefix sum

File: templates/prefix_sum.py

Recognition signals

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

Example problems

File: templates/binary_search.py

Recognition signals

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

Example problems

6. Monotonic stack and deque

File: templates/monotonic_stack.py

Recognition signals

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

Example problems

7. Merge intervals

File: templates/intervals.py

Recognition signals

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

Example problems

8. Cyclic sort

File: templates/cyclic_sort.py

Recognition signals

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

Example problems

9. In-place linked list reversal

File: templates/linked_list_reversal.py

Recognition signals

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

Example problems

10. Tree DFS

File: templates/tree_dfs.py

Recognition signals

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

Example problems

11. Tree BFS

File: templates/tree_bfs.py

Recognition signals

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

Example problems

12. Graph and grid traversal

File: templates/graph_traversal.py

Recognition signals

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

Example problems

13. Topological sort

File: templates/topological_sort.py

Recognition signals

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

Example problems

14. Union-find

File: templates/union_find.py

Recognition signals

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

Example problems

15. Top K elements

File: templates/top_k_heap.py

Recognition signals

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

Example problems

16. K-way merge

File: templates/k_way_merge.py

Recognition signals

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

Example problems

17. Two heaps

File: templates/two_heaps.py

Recognition signals

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

Example problems

18. Backtracking

File: templates/backtracking.py

Recognition signals

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

Example problems

19. Dynamic programming

File: templates/dynamic_programming.py

Recognition signals

The five-step recipe

  1. State: what does dp[i] (or dp[i][j]) mean, in one sentence?
  2. Transition: how is a state computed from smaller states?
  3. Base cases: the smallest states you know directly.
  4. Order: fill states so dependencies are ready (usually increasing i).
  5. 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

Example problems

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

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

Example problems

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

Learn the algorithms underneath the patterns

Python references

More practice beyond LeetCode

Contributing

Pull requests are welcome. Please keep entries accurate:

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.