Lesson 4 of 16 intermediate

LeetCode Strategy: Pattern-Based Approach

Stop solving random problems — learn 15 patterns that cover 90% of coding interviews

Open interactive version (quiz + challenge)

Real-world analogy

Solving random LeetCode problems is like studying for a math exam by doing random problems from random chapters. You might solve 500 and still fail. But if you learn the 15 core formulas and recognize which formula applies to each problem — you can solve almost anything with just 75-100 problems practiced.

What is it?

Pattern-based LeetCode preparation is a strategic approach to coding interview prep that focuses on learning reusable problem-solving patterns rather than memorizing individual solutions. Instead of grinding 1000 random problems, you learn 15 core patterns and practice recognizing which pattern applies to each new problem you encounter.

Real-world relevance

A developer spent 6 months solving 700 random LeetCode problems but failed 3 Google interviews because she couldn't solve novel variations. She then switched to pattern-based prep, solved 100 problems organized by pattern, and passed her next interview at Meta. The difference wasn't more practice — it was smarter practice.

Key points

Code example

# LeetCode Pattern Cheat Sheet
# ================================

# PATTERN 1: Two Pointers
# Use when: sorted array, find pairs, remove duplicates
# Key insight: Two pointers moving toward each other or same direction
# Classic problems: Two Sum II, 3Sum, Container With Most Water
# Template:
\`\`\`
left, right = 0, len(arr) - 1
while left < right:
    if condition_met: return result
    elif need_bigger: left += 1
    else: right -= 1
\`\`\`

# PATTERN 2: Sliding Window
# Use when: contiguous subarray/substring, max/min of window
# Key insight: Expand window right, shrink from left
# Classic: Max Subarray Sum of Size K, Longest Substring Without Repeat
# Template:
\`\`\`
window_start = 0
for window_end in range(len(arr)):
    # Add arr[window_end] to window
    while window_needs_shrinking:
        # Remove arr[window_start] from window
        window_start += 1
    # Update result
\`\`\`

# PATTERN 3: BFS (Level-Order Traversal)
# Use when: shortest path, level-by-level processing
# Key insight: Queue-based, process all nodes at current level
# Classic: Binary Tree Level Order, Shortest Path in Grid
# Template:
\`\`\`
queue = deque([start])
visited = set([start])
while queue:
    level_size = len(queue)
    for _ in range(level_size):
        node = queue.popleft()
        for neighbor in get_neighbors(node):
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
\`\`\`

# PATTERN 4: DFS (Depth-First Search)
# Use when: explore all paths, tree traversal, backtracking
# Key insight: Stack-based (or recursion), go deep before wide
# Classic: Path Sum, Number of Islands, Permutations
# Template:
\`\`\`
def dfs(node, path, result):
    if is_leaf(node):
        result.append(path[:])
        return
    for next_node in get_neighbors(node):
        path.append(next_node)
        dfs(next_node, path, result)
        path.pop()  # backtrack
\`\`\`

# PATTERN 5: Dynamic Programming
# Use when: overlapping subproblems, optimal substructure
# Key insight: Solve small → build up. Memoize or tabulate.
# Classic: Climbing Stairs, Coin Change, Longest Common Subsequence
# Template:
\`\`\`
dp = [base_case] * (n + 1)
for i in range(1, n + 1):
    dp[i] = recurrence_relation(dp[i-1], dp[i-2], ...)
return dp[n]
\`\`\`

# =========================
# PATTERN RECOGNITION GUIDE
# =========================
# "Find pair in sorted array" → Two Pointers
# "Contiguous subarray with condition" → Sliding Window
# "Shortest path / minimum steps" → BFS
# "All paths / combinations / permutations" → DFS/Backtracking
# "Overlapping subproblems" → Dynamic Programming
# "Top/Bottom K elements" → Heap
# "Find in sorted array" → Modified Binary Search
# "Merge sorted lists/arrays" → K-way Merge
# "Build order / dependencies" → Topological Sort

Line-by-line walkthrough

  1. 1. Two Pointers template: Initialize left at start, right at end. Move them toward each other based on conditions.
  2. 2. This works because the array is sorted — if sum is too small, move left up; if too big, move right down.
  3. 3. Sliding Window template: Expand the window by moving the right pointer. Shrink from left when the window violates constraints.
  4. 4. This achieves O(n) instead of O(n²) by avoiding redundant computation of overlapping subarrays.
  5. 5. BFS template: Use a queue, process level by level. Track visited nodes to avoid cycles.
  6. 6. BFS guarantees shortest path in unweighted graphs — DFS does not.
  7. 7. DFS template: Go deep using recursion, backtrack by removing the last choice when you hit a dead end.
  8. 8. DP template: Start with base cases, build up solutions to larger problems using previously computed results.
  9. 9. The pattern recognition guide at the bottom is the real gem — memorize these mappings for instant pattern identification.

Spot the bug

# Trying to find two numbers that sum to target in sorted array
def two_sum(arr, target):
    for i in range(len(arr)):
        for j in range(len(arr)):
            if arr[i] + arr[j] == target:
                return [i, j]
    return []
Need a hint?
This solution has 3 problems: wrong time complexity, a logical bug with using the same element twice, and it ignores the fact that the array is sorted. How would you fix it using the Two Pointers pattern?
Show answer
Problems: (1) O(n²) brute force when O(n) is possible with Two Pointers since array is sorted. (2) j starts at 0 so i could equal j, using the same element twice. (3) Doesn't leverage the sorted property. Fix: Use two pointers (left=0, right=len-1). If sum < target, left++. If sum > target, right--. If sum == target, return [left, right]. O(n) time, O(1) space.

Explain like I'm 5

Imagine you're learning to solve jigsaw puzzles. If someone gives you 500 random puzzles, you'll struggle with each one. But if someone teaches you: 'corners first, then edges, then group by color' — suddenly you can solve ANY puzzle using those 3 tricks. Coding patterns are like puzzle-solving tricks!

Fun fact

LeetCode has over 3,000 problems, but data from thousands of FAANG interviews shows that roughly 200 problems (organized into 15 patterns) cover over 90% of all questions asked. The company's premium subscription has a 'sort by frequency' feature that shows which problems are actually asked at specific companies.

Hands-on challenge

Create a LeetCode tracking spreadsheet with columns: Problem Name, Pattern, Difficulty, Date Solved, Time Taken, Solved Without Help (Y/N), Next Review Date. Solve these 3 problems today using the patterns from this lesson: (1) Two Sum II - Input Array Is Sorted (Two Pointers), (2) Maximum Subarray (Sliding Window/DP), (3) Binary Tree Level Order Traversal (BFS). For each, identify the pattern BEFORE coding, write pseudocode first, then implement.

More resources

Open interactive version (quiz + challenge) ← Back to course: Career Launchpad