download

Coding Interview Patterns Quick Reference: 17 LeetCode Patterns with Python Templates

#13Updated October 21, 202620 min read4,366 words

Python templates unchanged from October 20 checks

You see "shortest subarray" and reach for a sliding window. It worked yesterday. Then the interviewer allows negative numbers, and removing the leftmost value can make the sum larger. The familiar template is still familiar. Its reason for working has disappeared.

Patterns are useful hypotheses. The constraints and the invariant decide whether a hypothesis survives. Once you can explain why an index never needs to move backward, or why a discarded candidate can't matter later, the code becomes easier to reconstruct and much easier to adapt.

This guide gives you 17 patterns, Python templates, complexity and classic problems, followed by resource comparisons and a sample study plan. Use the signals to choose what to investigate, then check why it applies.


Pattern recognition: the decision table

Use a row as a first hypothesis, then check its conditions. Many problems match two rows. Hard problems often combine patterns, for example binary search on the answer with a greedy check.

If the problem says or implies…Try firstTypical complexity
Sorted array, a pair, or in-place processingTwo pointersO(n) for the pair/single pass; 3Sum adds an outer loop, O(n²)
Longest/shortest contiguous subarray or substring with a conditionSliding windowO(n)
Sum of a subarray, many range-sum queries, "subarray sum equals k"Prefix sums + hash mapO(n)
"Have we seen this before?", counting, grouping, pairs summing to a targetHash map / setO(n)
Sorted input, or "minimum X such that…" / "maximum X such that…"Binary search (on index or on the answer)O(log n) or O(n log M)
Fewest steps, shortest path in an unweighted graph or grid, level by levelBFSO(V + E)
All combinations, permutations, subsets, "generate all valid…"Backtracking (DFS)Exponential
Connected regions in a grid, "number of islands"DFS or BFS flood fillO(rows × cols)
Dependencies, prerequisites, "order of tasks", detect a cycle in a directed graphTopological sortO(V + E)
"Are these connected?", merging groups, redundant edgeUnion-find~O(1) per operation
K largest / smallest, merge K lists, running medianHeapFixed top-k: O(n log k); merge: O(N log k); median: O(log n) per insert
Overlapping ranges, meetings, merging or inserting intervalsSort + sweep (intervals)O(n log n)
"Next greater/smaller element", spans, histogram areasMonotonic stackO(n)
Binary tree or BST: depth, paths, validation, ancestorsTree DFS / BFSO(n)
Prefix search, autocomplete, many words against one dictionaryTrieO(length) per word
"Number of ways", "minimum cost", "longest…", choices that overlapDynamic programmingUsually O(n) to O(n × m)
A locally best choice is provably safe (earliest end, farthest reach)GreedyO(n) or O(n log n)
Shortest path with non-negative weightsDijkstraO((V + E) log V)

Two quick heuristics help when nothing jumps out. Look at the constraints: n ≤ 20 usually allows exponential backtracking, n around 10⁵ needs O(n log n) or better, and values up to 10⁹ with a "minimum possible" question point to binary search on the answer. Ask what a brute force would repeat: a repeated sum suggests prefix sums, a repeated lookup suggests a hash map, and repeated subproblems suggest DP.


1. Two pointers

In a sorted pair search, a sum that is too small lets you discard the entire left value with the current right boundary: every smaller right value would also fail. That exclusion is the reason the pointer can move.

Spot it: a sorted array or string; find a pair or triplet with a target sum; reverse or compare from both ends; remove items in place; a linked list cycle or middle node (fast and slow pointers).

"PYTHON"
def pair_with_sum(nums, target):
    """nums is sorted. Return indices (i, j) with nums[i] + nums[j] == target, or None."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

def remove_duplicates(nums):
    """Same-direction pointers: dedupe a sorted list in place, return the new length."""
    write = 0
    for read in range(len(nums)):
        if write == 0 or nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

def has_cycle(head):
    """Fast/slow pointers on a linked list whose nodes have a .next attribute."""
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False

Complexity: O(n) time, O(1) extra space for these templates. 3Sum fixes one element and scans the remaining pair, usually O(n²) overall. Classic problems: Two Sum II – Input Array Is Sorted, 3Sum, Container With Most Water, Linked List Cycle.

2. Sliding window

Spot it: a contiguous range whose endpoints can move forward without losing a possible answer. For at-most-k distinct characters, expansion can violate the limit and shrinking restores it. For a minimum sum with positive values, expansion reaches the threshold, then shrinking searches for a shorter valid range. Those are different invariants, not one rule that expansion always makes a window more invalid. The template below assumes k ≥ 0.

"PYTHON"
def longest_at_most_k_distinct(s, k):
    """Length of the longest substring with at most k distinct characters."""
    count = {}
    left = best = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        while len(count) > k:            # window is invalid: shrink from the left
            out = s[left]
            count[out] -= 1
            if count[out] == 0:
                del count[out]
            left += 1
        best = max(best, right - left + 1)
    return best

Complexity: O(n) time, because each index enters and leaves the window at most once. Space is O(k) for the counter. Classic problems: Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Repeating Character Replacement, Minimum Size Subarray Sum.

Negative values can break the monotonic sum reasoning: dropping a negative value increases the sum. For counting subarrays summing to k with arbitrary signs, prefix sums plus a map preserve the information a window discards.

3. Prefix sums

A range sum is the difference between two prefix sums. To find a range ending here with sum k, ask whether the earlier prefix current−k has appeared. The map keeps earlier possibilities even when values change sign.

Spot it: many range-sum queries on a static array; "subarray sum equals k"; "subarray divisible by k"; balance problems such as equal 0s and 1s.

"PYTHON"
def subarray_sum_count(nums, k):
    """Number of contiguous subarrays that sum to k (works with negative numbers)."""
    seen = {0: 1}               # prefix sum -> how many times it has occurred
    total = count = 0
    for x in nums:
        total += x
        count += seen.get(total - k, 0)
        seen[total] = seen.get(total, 0) + 1
    return count

Complexity: O(n) time and O(n) space. For range queries, store prefix[i+1] = prefix[i] + nums[i]; then sum(nums[i:j]) is prefix[j] - prefix[i] in O(1). Classic problems: Subarray Sum Equals K, Range Sum Query – Immutable, Product of Array Except Self (the same idea with products), Contiguous Array.

4. Hashing (hash maps and sets)

A useful key replaces repeated searching with a lookup. Decide what the key means before writing the map: a value, a frequency or a canonical description of a group. Equal keys must represent the equivalence you actually want.

Spot it: "find a pair", "contains duplicate", counting frequencies, grouping items by a key, or any brute force that repeats the same lookup.

"PYTHON"
from collections import defaultdict

def two_sum(nums, target):
    index = {}                          # value -> index where we saw it
    for i, x in enumerate(nums):
        if target - x in index:
            return index[target - x], i
        index[x] = i
    return None

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups[tuple(sorted(w))].append(w)   # same letters -> same key
    return list(groups.values())

Complexity: Two Sum is O(n) time and O(n) space on average. Group Anagrams is O(n · m log m) for n words of length m. A 26-letter count as the key makes it O(n · m). Classic problems: Two Sum, Group Anagrams, Contains Duplicate, Longest Consecutive Sequence.

5. Binary search, including binary search on the answer

The predicate does the important work. If a larger capacity can fail after a smaller one succeeds, there is no false-to-true boundary to search. For the Koko helper, assume nonempty positive piles and h ≥ len(piles), so the upper endpoint is feasible.

Spot it: a sorted array, or a rotated one; "first/last position of"; and the less obvious version: "minimum speed / capacity / days such that…". If a guess x either works or doesn't, and every larger x also works, binary search over x.

"PYTHON"
def lower_bound(nums, target):
    """First index i with nums[i] >= target (len(nums) if there is none)."""
    lo, hi = 0, len(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

def min_feasible(lo, hi, feasible):
    """Smallest x in [lo, hi] with feasible(x) True.
    feasible must be monotonic (False ... False True ... True) and feasible(hi) True."""
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

def min_eating_speed(piles, h):
    """Koko Eating Bananas: slowest speed that finishes all piles in h hours."""
    return min_feasible(1, max(piles),
                        lambda v: sum((p + v - 1) // v for p in piles) <= h)

Complexity: O(log n) for a sorted array. On the answer, it's O(log M) checks, where M is the size of the search range. Each check costs O(n) for Koko, so O(n log M) in total. Classic problems: Binary Search, Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array, Koko Eating Bananas, Capacity To Ship Packages Within D Days.

Python's bisect.bisect_left does the same job as lower_bound. Writing it by hand in an interview shows you understand the loop invariant.

6. Breadth-first search (BFS)

The queue processes distances in increasing edge count. Marking a node when you enqueue it prevents several paths from scheduling it repeatedly. The grid helper assumes a nonempty rectangular grid and valid open start and goal coordinates; its edges all cost one move.

Spot it: "minimum number of steps/moves/transformations", shortest path in an unweighted grid or graph, "level by level", or spreading from several sources at once (multi-source BFS, as in Rotting Oranges).

"PYTHON"
from collections import deque

def shortest_path_grid(grid, start, goal):
    """Fewest moves from start to goal in a grid of '.' (open) and '#' (wall); -1 if unreachable."""
    rows, cols = len(grid), len(grid[0])
    queue = deque([(start, 0)])
    seen = {start}
    while queue:
        (r, c), dist = queue.popleft()
        if (r, c) == goal:
            return dist
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if (0 <= nr < rows and 0 <= nc < cols
                    and grid[nr][nc] != '#' and (nr, nc) not in seen):
                seen.add((nr, nc))          # mark when enqueued, not when popped
                queue.append(((nr, nc), dist + 1))
    return -1

Complexity: O(V + E) time and O(V) space; on a grid, O(rows × cols). Classic problems: Binary Tree Level Order Traversal, Rotting Oranges, Word Ladder, Shortest Path in Binary Matrix.

7. DFS and backtracking

The path describes one partial choice. Append, explore, then undo exactly that change before trying the next branch. A missing undo can make a correct recurrence produce answers belonging to several branches at once.

Spot it: "return all…", "generate every valid…", subsets, permutations, combinations, N-Queens, word search in a grid. Plain DFS also covers reachability and connected components ("number of islands"). The num_islands template below assumes a nonempty rectangular grid and mutates it to mark visited cells.

"PYTHON"
def subsets(nums):
    result, path = [], []
    def backtrack(start):
        result.append(path[:])            # every partial path is a subset
        for i in range(start, len(nums)):
            path.append(nums[i])          # choose
            backtrack(i + 1)              # explore
            path.pop()                    # un-choose
    backtrack(0)
    return result

def num_islands(grid):
    """grid of '1' (land) and '0' (water); modified in place."""
    rows, cols = len(grid), len(grid[0])
    def sink(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1':
            return
        grid[r][c] = '0'
        sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1)
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                sink(r, c)
                count += 1
    return count

For permutations, keep a used array instead of a start index and record the path when its length reaches n.

Complexity: subsets O(n · 2ⁿ), permutations O(n · n!), number of islands O(rows × cols). On a large island the recursion can hit Python's recursion limit, so offer an iterative stack or BFS. Classic problems: Subsets, Permutations, Combination Sum, Word Search, Number of Islands, N-Queens.

8. Topological sort

Indegree counts prerequisites that remain. Removing a zero-indegree node can free its dependants. If nodes remain with no available starting point, a directed cycle prevents the requested ordering.

Spot it: prerequisites, build order, "task A must happen before task B", "is it possible to finish all courses", or ordering letters in an alien dictionary. Anything that is a directed graph with a required order.

"PYTHON"
from collections import deque

def topo_order(n, edges):
    """Kahn's algorithm. edges: (u, v) means u must come before v.
    Returns an order of 0..n-1; if len(order) < n, the graph has a cycle."""
    graph = [[] for _ in range(n)]
    indegree = [0] * n
    for u, v in edges:
        graph[u].append(v)
        indegree[v] += 1
    queue = deque(i for i in range(n) if indegree[i] == 0)
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in graph[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)
    return order

Complexity: O(V + E) time and space. Classic problems: Course Schedule, Course Schedule II, Alien Dictionary, Parallel Courses.

9. Union-find (disjoint set union)

Each representative names a component. Path compression makes later lookups cheaper, while union by size keeps trees shallow. The structure answers connectivity; it does not retain the path connecting two nodes.

Spot it: "are these two connected?", count groups as edges arrive, find the edge that creates a cycle in an undirected graph, merge accounts that share an email.

"PYTHON"
class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        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, b):
        """Merge the sets of a and b. Returns False if they were already connected."""
        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                # attach the smaller tree under the larger
        self.size[ra] += self.size[rb]
        return True

Complexity: with union by size and path halving, each operation is amortized O(α(n)), the inverse Ackermann function. In practice that's constant. Space is O(n). Classic problems: Number of Provinces, Redundant Connection, Number of Connected Components in an Undirected Graph, Accounts Merge.

10. Heaps and top-K

For the largest k values, a min-heap keeps the smallest retained value at the boundary. A new value only matters if it can displace that boundary. A running median needs two heaps containing the whole stream, a different space model from retaining only k values.

Spot it: "k largest / smallest / closest / most frequent", "kth largest", merge k sorted lists, a running median, or always processing the cheapest/earliest item next.

"PYTHON"
import heapq
from collections import Counter

def k_largest(nums, k):
    heap = []                          # min-heap holding the k largest seen so far
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)        # drop the smallest
    return sorted(heap, reverse=True)  # heap[0] alone is the kth largest

def top_k_frequent(nums, k):
    return [x for x, _ in Counter(nums).most_common(k)]

Complexity: k_largest uses O(n log k) time and O(k) extra space. The Counter-based frequent-elements helper stores all d distinct keys: O(d) space, plus selection work. Merge k lists uses a heap of k heads; a running median usually stores O(n) values. These aren't one shared heap bound. Classic problems: Kth Largest Element in an Array, Top K Frequent Elements, K Closest Points to Origin, Merge k Sorted Lists, Find Median from Data Stream.

11. Intervals

Sorting creates an order in which a sweep can settle earlier decisions. Specify whether touching endpoints overlap: a meeting ending exactly when another begins need not require another room, while an interval union may choose to merge touching ranges.

Spot it: pairs of start/end times; meetings, bookings, ranges; "merge", "insert", "overlap", "minimum rooms". Almost always: sort by start or by end first.

"PYTHON"
import heapq

def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:       # overlaps the last one
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

def min_meeting_rooms(intervals):
    """Meetings are [start, end); a room frees up exactly at end."""
    ends = []                                       # min-heap of end times in use
    for start, end in sorted(intervals):
        if ends and ends[0] <= start:
            heapq.heapreplace(ends, end)            # reuse the room that frees first
        else:
            heapq.heappush(ends, end)
    return len(ends)

Complexity: O(n log n) for the sort; the sweep itself is O(n), or O(n log n) with the heap. Space O(n). Classic problems: Merge Intervals, Insert Interval, Non-overlapping Intervals, Meeting Rooms II.

12. Monotonic stack

An index stays on the stack while its answer is unresolved. When a warmer day arrives, it can resolve several waiting indices, each only once. That is why the nested loop can still do linear total work.

Spot it: "next greater element", "how many days until a warmer temperature", stock span, "largest rectangle in a histogram", trapping rain water. Any time you want the nearest larger or smaller element to the left or right.

"PYTHON"
def daily_temperatures(temps):
    answer = [0] * len(temps)
    stack = []                       # indices whose temperatures are decreasing
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            answer[j] = i - j        # i is the next warmer day for j
        stack.append(i)
    return answer

Complexity: O(n) time, amortized. Each index is pushed and popped at most once. O(n) space. Classic problems: Daily Temperatures, Next Greater Element I, Online Stock Span, Largest Rectangle in Histogram.

13. Trees (DFS and BFS on binary trees)

Choose the direction information must travel. A subtree height comes up from children; a BST bound comes down from ancestors. Keeping that meaning clear is more useful than remembering which traversal name goes with a problem.

Spot it: the input is a TreeNode. Ask: does the answer for a node come from its children (post-order DFS), from its ancestors (pass values down), or from its level (BFS)?

"PYTHON"
from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def max_depth(root):
    if not root:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

def is_valid_bst(root, lo=float('-inf'), hi=float('inf')):
    if not root:
        return True
    if not lo < root.val < hi:
        return False
    return (is_valid_bst(root.left, lo, root.val)
            and is_valid_bst(root.right, root.val, hi))

def level_order(root):
    if not root:
        return []
    levels, queue = [], deque([root])
    while queue:
        level = []
        for _ in range(len(queue)):          # exactly one level per pass
            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. Space is O(h) for DFS (h = height: log n if balanced, n if skewed) and O(w) for BFS (w = widest level). Classic problems: Maximum Depth of Binary Tree, Validate Binary Search Tree, Lowest Common Ancestor of a Binary Tree, Binary Tree Maximum Path Sum, Serialize and Deserialize Binary Tree.

14. Tries (prefix trees)

Shared prefixes share nodes, so a prefix lookup follows the input characters rather than comparing the whole dictionary. An end-of-word marker separates a stored word from a path that merely begins a longer one.

Spot it: prefix search, autocomplete, "starts with", or searching many words in one grid or dictionary (Word Search II).

"PYTHON"
class TrieNode:
    __slots__ = ("children", "is_word")
    def __init__(self):
        self.children = {}
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.is_word = True

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return node is not None and node.is_word

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

Complexity: O(L) time per operation for a word of length L. Space is O(total characters inserted). Classic problems: Implement Trie (Prefix Tree), Design Add and Search Words Data Structure, Word Search II, Search Suggestions System.

15. Dynamic programming: the key subtypes

A state is useful only if it contains enough information to decide the next step. State its meaning and the base case before the transition. Coin Change assumes positive coin values and a nonnegative integer amount.

Spot it: "number of ways", "minimum/maximum cost", "longest/shortest…", "can you reach…", where choices overlap: the brute force recomputes the same subproblem. Define the state (what dp[i] means), the transition, and the base case, in that order, out loud.

SubtypeStateClassic problems
1-D linearbest answer for the first i itemsClimbing Stairs, House Robber, Decode Ways
Unbounded knapsackbest answer for amount a, items reusableCoin Change, Coin Change II, Perfect Squares
0/1 knapsackbest answer for capacity c, each item oncePartition Equal Subset Sum, Target Sum
Two sequences (2-D)answer for prefixes a[:i], b[:j]Longest Common Subsequence, Edit Distance
Gridanswer for cell (r, c)Unique Paths, Minimum Path Sum
LIS familybest sequence ending at iLongest Increasing Subsequence, Russian Doll Envelopes
Interval DPanswer for range i..jLongest Palindromic Substring, Burst Balloons
"PYTHON"
from bisect import bisect_left

def rob(nums):
    """House Robber, 1-D with O(1) space."""
    take = skip = 0          # best total if the previous house was robbed / skipped
    for x in nums:
        take, skip = skip + x, max(take, skip)
    return max(take, skip)

def coin_change(coins, amount):
    """Unbounded knapsack: fewest coins for amount, or -1."""
    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] <= amount else -1

def knapsack(weights, values, capacity):
    """0/1 knapsack: iterate capacity backwards so each item is used at most once."""
    dp = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for c in range(capacity, w - 1, -1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[capacity]

def lcs(a, b):
    """Longest Common Subsequence, 2-D table over prefixes."""
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[-1][-1]

def lis_length(nums):
    """Longest strictly increasing subsequence in O(n log n)."""
    tails = []               # tails[k] = smallest tail of an increasing run of length k+1
    for x in nums:
        i = bisect_left(tails, x)
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)

Complexity: House Robber O(n) time, O(1) space. Coin Change O(amount × number of coins) time, O(amount) space. 0/1 knapsack O(items × capacity) time, O(capacity) space. LCS O(m × n) time and space. LIS O(n log n) time, O(n) space.

Top-down works too: write the recursion, then add @functools.cache. In an interview, start top-down if it's easier to explain, then offer the bottom-up version and the space optimization as follow-ups.

16. Greedy

Try an exchange argument: can an optimal solution use the local choice without becoming worse? If you cannot show that, seek a small counterexample. Failure to find a proof does not establish that dynamic programming is the answer; reconsider the state and available structure.

Spot it: a choice that can be shown to be safe right now, such as "pick the interval that ends earliest" or "track the farthest index you can reach". Be ready to justify it: interviewers often ask "why is greedy correct here?" An unexplained local choice is still a hypothesis.

"PYTHON"
def can_jump(nums):
    reach = 0                          # farthest index reachable so far
    for i, step in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + step)
    return True

Complexity: O(n) time, O(1) space. Interval greedies (sort by end, keep what fits) are O(n log n) because of the sort. Classic problems: Jump Game, Jump Game II, Gas Station, Non-overlapping Intervals, Partition Labels.

17. Graphs: shortest paths with weights (Dijkstra)

With nonnegative edges, the smallest current distance can be settled before any longer route improves it. The heap may hold stale proposals; ignore those when popped. The template assumes node IDs can be compared on tied distances, as integers or strings can; mixed incomparable objects need a tie-breaker.

Spot it: a weighted graph and "cheapest/fastest path", "network delay", "minimum effort". Weights must be non-negative. With 0/1 weights, a deque (0-1 BFS) is faster. Negative edges need an appropriate method such as Bellman-Ford, with negative cycle handling. A stop/edge cap needs layered state or bounded relaxations; ordinary BFS minimizes edge count, not arbitrary weighted cost.

"PYTHON"
import heapq

def dijkstra(graph, source):
    """graph: {u: [(v, weight), ...]}, weights >= 0. Returns {node: shortest distance}."""
    dist = {source: 0}
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                   # stale entry: a shorter path was already found
        for v, w in graph.get(u, ()):
            nd = d + w
            if nd < dist.get(v, float('inf')):
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist

Complexity: O((V + E) log V) time with a binary heap, O(V + E) space. Classic problems: Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops (a variant), Swim in Rising Water.


Blind 75 vs Grind 75 vs NeetCode 150 vs LeetCode 75 vs Grokking

These are the lists and courses people compare most. The facts below were checked on each resource's own page in October 2026. Which one is "best" is up to you. The real difference is size, ordering and format.

ResourceWhat it isSizeDifficulty mixCost
Blind 75The original curated list of LeetCode problems by Yangshun Tay, first shared on the Blind forum7519 easy / 49 medium / 7 hard (as listed on neetcode.io)Free
Grind 75The Blind 75 author's newer, customizable plan: pick weeks, hours per week and topics, and it builds a schedule75 by default, up to 169Default set: 24 / 42 / 9Free; the core 75 has no premium questions
NeetCode 150Blind 75 plus 75 more problems, grouped into 18 topics, with video solutions15028 / 101 / 21Lists free; NeetCode Pro is a paid upgrade
NeetCode 250NeetCode 150 plus 100 more, described by NeetCode as its most beginner-friendly list25060 / 155 / 35Free list
LeetCode 75LeetCode's official study plan, in 22 topic groups7522 / 53 / 0On LeetCode
Top Interview 150LeetCode's larger official plan of "classic" questions15039 / 93 / 18On LeetCode
Grokking the Coding InterviewA course organized by pattern, from Design Gurus: lessons with in-browser playgrounds in six languages300+ problems, about 40 patterns—Paid: one-time purchase or subscription
Coding Interview Patterns (book)Alex Xu and Shaun Gunawardane, ByteByteGo, December 2024: 19 pattern chapters101 problems—Paid book

LeetCode recommends LeetCode 75 for one to three months of preparation and Top Interview 150 for three months or more. Grind 75's default schedule is 8 weeks at 8 hours a week.

Grokking the Coding Interview vs NeetCode. Grokking is a paid written course where each lesson teaches a pattern and then applies it. NeetCode is a free, topic-ordered list of LeetCode problems with a video explanation for each, plus paid courses in NeetCode Pro. Readers who want pattern-first text lean to Grokking; people who like video and solving on LeetCode lean to NeetCode.

LeetCode vs NeetCode. They aren't really alternatives. LeetCode is the platform: problem bank, judge, contests, company tags and official study plans. NeetCode is a separate site that curates which LeetCode problems to solve, explains them in videos, and hosts its own courses. Many people use NeetCode to choose and learn, and LeetCode to submit.

Is Blind 75 enough? If you know the basics and have a few weeks, it covers the core. But by NeetCode's grouping it has only two binary search problems and one heap problem, so add the classics from this page for thin patterns.

Useful GitHub repositories ("leetcode patterns github")


A six-week study plan

This sample plan assumes roughly 8–10 hours a week and familiarity with Python and Big-O. It follows the order patterns build on each other. Each week has one new block and one review block. The problem counts are targets to adjust when review or an unfamiliar concept takes longer.

WeekNew patternsProblems to solveReview
1Hashing, two pointers, sliding window, prefix sums12–15 easy/medium—
2Binary search (incl. on the answer), monotonic stack, intervals12–15Week 1 misses
3Trees (DFS/BFS), tries, heaps/top-K12–15Weeks 1–2
4Graph BFS/DFS, topological sort, union-find, Dijkstra12–15Weeks 2–3
5Backtracking, 1-D DP, knapsack DP10–12Weeks 3–4
62-D DP, greedy, mixed sets, two timed mock interviews10–12Everything you missed twice

That's roughly 70–85 problems, the size of the Blind 75 or Grind 75, but ordered by pattern. Two weeks only? Do weeks 1, 3 and 4 in the first week (top two or three problems per pattern), then 1-D DP, backtracking and timed mocks in the second.


How to practice: spaced repetition and timing

Revisiting a problem can reveal whether you learned its reasoning or only recognized the solution. Keep a mix of review and unfamiliar variants: recall helps you start, while a changed constraint tests what you understood.

Try spaced review. Log each problem with its pattern, the signal you missed, and the date. Re-solve it from a blank file after about 3 days, then 1 week, then 3 weeks. Clean solve: move to the next interval. Struggle: back to 3 days. A spreadsheet or flashcard app works. The card is "problem statement → which pattern and why", not the code.

Time yourself like a real round. Many companies use 45–60 minute coding interviews. Practice a medium problem on a timer:

MinutesWhat to do
0–5Restate the problem, ask about constraints and edge cases, do one example by hand
5–10Name the brute force and its complexity, then the pattern and the better complexity
10–30Write the code while explaining it
30–35Walk through a test case and the edge cases out loud; fix bugs
35+Follow-ups: space optimization, a variant, a scaling question

Set a stuck limit. No progress after 20–25 minutes? Read the solution, note which signal pointed to the pattern, and schedule a blank-file retry in 3 days. If you stop making progress, a hint can be more productive; afterward, explain what it revealed and solve a variant without that hint.

Talk out loud from day one. Interviewers score communication and testing, not just a passing solution. Do a mock interview with a friend every week.


Coding interview quick reference (summary)

"TEXT"
SORTED / PAIR / IN PLACE ........ two pointers            O(n); 3Sum usually O(n²)
CONTIGUOUS + CONDITION .......... sliding window          O(n)
SUBARRAY SUM = K (negatives) .... prefix sum + hash map   O(n)
SEEN BEFORE / COUNT / GROUP ..... hash map / set          O(n)
SORTED or "MIN X SUCH THAT" ..... binary search           O(log n) · O(n log M)
FEWEST STEPS, UNWEIGHTED ........ BFS                     O(V + E)
ALL COMBINATIONS / PERMUTATIONS . backtracking            O(n · 2^n) / O(n · n!)
PREREQUISITES / ORDER ........... topological sort        O(V + E)
CONNECTED? / MERGE GROUPS ....... union-find              ~O(1) amortized
K LARGEST / K MOST FREQUENT ..... heap                    O(n log k)
OVERLAPPING RANGES .............. sort + sweep            O(n log n)
NEXT GREATER / SMALLER .......... monotonic stack         O(n)
PREFIX / AUTOCOMPLETE ........... trie                    O(L)
WAYS / MIN COST / LONGEST ....... dynamic programming     state × transition
SAFE LOCAL CHOICE ............... greedy (prove it)       O(n log n)
WEIGHTED, NON-NEGATIVE .......... Dijkstra                O((V + E) log V)

FAQ

What are LeetCode patterns?

LeetCode patterns are recurring problem-solving techniques, such as two pointers, sliding window or topological sort, that solve whole families of interview problems. Learning to recognize the pattern from the problem statement is more useful than memorizing individual solutions.

How many coding interview patterns are there?

It depends on how finely you split them. Most guides list between about 14 and 40. This page groups the material into 17 patterns. Grokking's course page lists about 40, and the ByteByteGo book has 19 chapters.

How many LeetCode problems should I solve before an interview?

There's no official number. Curated lists put the core at 75–150 problems (Blind 75, Grind 75, NeetCode 150, LeetCode 75). Coverage of every pattern and the ability to re-solve problems from scratch matter more than the total count.

Is LeetCode good for beginners?

Yes, but start in the right place. If you are new to data structures, learn the basics first (arrays, hash maps, stacks, trees, graphs, Big-O), then use a beginner-friendly list such as NeetCode 250 or LeetCode 75, which has no hard problems. A hard problem is useful practice once you can understand which missing idea made it hard; otherwise, step back to a smaller example.

Is LeetCode worth it in 2026?

For roles with algorithmic coding rounds, yes: the patterns on this page still come up. Some companies are adding other formats, such as practical coding or AI-assisted rounds, so check the format with your recruiter and don't prepare only for algorithm puzzles.

What language should I use for LeetCode and coding interviews?

Use the language you're fastest and most accurate in, as long as the company allows it. Python is popular because it's short and its standard library covers heaps, deques, counters and binary search. Know your language's equivalents of the imports in these templates.

How do I start with LeetCode?

Pick one list and work pattern by pattern: 2–3 easy problems first, then the medium classics. Log every problem and re-solve it later from a blank file.

Grokking the Coding Interview or NeetCode?

Both cover the same core patterns. Grokking is paid, text-based and organized by pattern; NeetCode's lists and videos are free, with a paid Pro tier. Choose by format (text or video) and budget.