CS concepts

7 LeetCode Patterns Explained: How to Spot Each One

Updated Nov 27, 2026 · 5 min read

Seven patterns cover most coding interview questions: hash map, two pointers, sliding window, binary search, BFS/DFS, heap and dynamic programming. The question's wording gives the pattern away: a pair or seen before means hash map, longest substring means sliding window, sorted or rotated means binary search, and how many ways means DP. Name the pattern first, and the code is short.

Watch onYouTubeInstagram

Key points

  • ●Pair or seen before: hash map. Sorted pairs: two pointers.
  • ●Longest substring: sliding window. Sorted or rotated: binary search.
  • ●Grid or tree: BFS or DFS. Top k: heap. How many ways or best total: DP.
  • ●Each pattern has one classic trap, like storing before checking in Two Sum.
  • ●Before writing code on a new problem, name its pattern.
Step-by-step visual sheet: 7 LeetCode Patterns
The full visual sheet, made with Edithly.Open the interactive sheet

The slow way: 500 problems

Here's a list of a thousand numbers. Find two that add up to a target. Check every pair and that's 499,500 checks. Walk the list once with the right trick and it's a thousand looks.

The difference isn't talent. It's knowing the pattern. Interview questions reuse a small set of tricks with new stories wrapped around them, and the wording tells you which trick to use. Below, for each of seven patterns: the giveaway words, one Blind 75 problem, a tiny example, the code skeleton and the trap. The visual sheet above has all seven on one page.

1. Hash map

Giveaway words: find a pair, seen before, count, duplicate.

Two Sum: find two numbers that add up to a target. With [2, 7, 11, 15] and target 9: at 2 you need 7, not seen, so store 2. At 7 you need 2, seen at index 0. Answer [0, 1].

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i

Trap: check before you store. Store first and a number can pair with itself. O(n²) becomes O(n). Contains Duplicate is the same move with a set.

2. Two pointers

Giveaway words: sorted array, pair, triplet, palindrome, container.

Container With Most Water: pick two fence posts and hold the most water between them. The water can only rise to the shorter post, so moving the taller one inward can never help. Move the shorter one.

Posts [3, 7, 2, 6, 4, 5]: the ends give min(3, 5) × 5 = 15. Move the 3 in: min(7, 5) × 4 = 20. Nothing later beats 20. Fifteen pairs, five looks.

def max_area(h):
    l, r = 0, len(h) - 1
    best = 0
    while l < r:
        best = max(best, min(h[l], h[r]) * (r - l))
        if h[l] <= h[r]: l += 1
        else: r -= 1
    return best

Trap: two pointers needs a reason to throw one side away. Here it's that the shorter post caps the water. 3Sum uses the same idea after sorting: fix one number, two-pointer the rest.

3. Sliding window

Giveaway words: longest, shortest, substring, subarray, at most k.

Longest Substring Without Repeating Characters: grow the right edge one letter at a time. Hit a letter already in the window? Jump the left edge just past where it was last seen. On "abcabcbb" the window reaches abc, then slides along and never beats 3.

def length_of_longest_substring(s):
    seen, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if seen.get(ch, -1) >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best

Trap: the left edge only moves forward. That's what the >= left check is for. Each letter enters and leaves once, so it's one pass instead of O(n²) windows.

Giveaway words: sorted, rotated, find the minimum, and "in O(log n) time".

Find Minimum in Rotated Sorted Array: a sorted list was cut and its halves swapped. If the middle is bigger than the right end, the drop is on the right. Otherwise the minimum is the middle or to its left. On [4, 5, 6, 7, 0, 1, 2]: middle 7 > 2, go right. Middle 1 < 2, keep left. Land on 0.

def find_min(nums):
    l, r = 0, len(nums) - 1
    while l < r:
        m = (l + r) // 2
        if nums[m] > nums[r]: l = m + 1
        else: r = m
    return nums[l]

Trap: compare with the right end, not the left, or a list that was never rotated breaks it. A billion numbers takes about 30 looks.

5. BFS and DFS

Giveaway words: grid, islands, connected, tree, shortest path.

Number of Islands: a grid of ones (land) and zeros (water). Scan it. When you hit land, count one island, then sink it: turn every connected land cell into water. The next land you find must be a new island.

def num_islands(g):
    R, C = len(g), len(g[0])
    def sink(r, c):
        if 0 <= r < R and 0 <= c < C and g[r][c] == "1":
            g[r][c] = "0"
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                sink(r + dr, c + dc)
    count = 0
    for r in range(R):
        for c in range(C):
            if g[r][c] == "1":
                count += 1
                sink(r, c)
    return count

Trap: forget to mark a cell visited and you walk in circles. Sinking it is the mark. O(rows × columns). For a shortest path, use the same walk with a queue, one ring at a time: that's BFS.

6. Heap

Giveaway words: k largest, k most frequent, k closest, median.

Top K Frequent Elements: count with a hash map, then keep only the k biggest counts. With [1, 1, 1, 2, 2, 3] and k = 2, the counts are 3, 2 and 1, so the answer is [1, 2].

from collections import Counter
import heapq

def top_k_frequent(nums, k):
    count = Counter(nums)
    return heapq.nlargest(k, count, key=count.get)

Trap: a heap holding everything is just sorting with extra steps. Keep it at size k.

7. Dynamic programming

Giveaway words: how many ways, maximum total, minimum cost.

Maximum Subarray: at each number, ask whether the run so far helps or you should start fresh. On [-2, 1, -3, 4, -1, 2, 1, -5, 4] the run is negative before 4, so start fresh there: 4, 3, 5, 6. Best is 6.

def max_subarray(nums):
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

Trap: start best at the first number, not zero, or an all-negative list returns 0. Climbing Stairs and Coin Change have the same shape: the answer now is built from answers you already have.

The whole thing in one breath

  • Pair, or seen before: hash map
  • Sorted pairs: two pointers
  • Longest substring: sliding window
  • Sorted or rotated: binary search
  • Grid or tree: BFS or DFS
  • Top k: heap
  • How many ways, or best total: dynamic programming

Pick one problem tonight. Before you write any code, name its pattern.

Frequently asked questions

What are the 7 main LeetCode patterns?

Hash map, two pointers, sliding window, binary search, BFS/DFS, heap (top K) and dynamic programming. The first four handle most array and string questions; the last three handle grids, trees, top k and counting or optimizing problems.

How do I recognize which pattern a problem needs?

Look for the giveaway words. "Find a pair" or "seen before": hash map. "Sorted", "triplet", "palindrome", "container": two pointers. "Longest", "substring", "at most k": sliding window. "Rotated" or "in O(log n) time": binary search. "Grid", "islands", "tree": BFS/DFS. "k largest", "k most frequent": heap. "How many ways", "minimum cost": DP.

Why is Two Sum O(n) with a hash map?

You walk the list once and ask a dictionary whether the number you need is already there. Each lookup is O(1) on average, so a thousand numbers take a thousand looks instead of 499,500 pair checks.

Is Kadane's algorithm dynamic programming?

Yes. At each number you decide whether to extend the run or start fresh, and each answer is built from the one right before it. That reuse of the previous answer is what makes it DP.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free