Lesson 5 of 16 advanced

Top Interview Coding Patterns

Master the exact patterns that appear in 90% of technical interviews at top companies

Open interactive version (quiz + challenge)

Real-world analogy

Coding patterns are like martial arts kata — choreographed sequences of moves. A karate master doesn't think about each punch individually in a fight; they recognize the situation and flow into the right kata instinctively. Similarly, top interviewees don't solve each problem from scratch — they recognize the pattern and apply the template.

What is it?

Interview coding patterns are reusable algorithmic templates that solve broad categories of problems. Instead of memorizing solutions to 1000 individual problems, mastering 10-15 patterns gives you the tools to solve virtually any problem an interviewer throws at you. Each pattern has a recognizable trigger (problem description keywords), a template (code structure), and variations (twists interviewers add).

Real-world relevance

Google's interview process has been studied extensively. Analysis of thousands of interview questions shows that 15 patterns cover approximately 90% of all coding questions asked at FAANG companies. A former Google interviewer revealed that they deliberately pick problems that test pattern recognition — they want to see if you can identify the underlying structure, not just brute-force a solution.

Key points

Code example

# Complete Pattern Templates for Top Interview Patterns
# =====================================================

# 1. TWO POINTERS: Pair with Target Sum (Sorted Array)
\`\`\`python
def pair_with_target(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        current_sum = arr[left] + arr[right]
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1    # Need bigger sum
        else:
            right -= 1   # Need smaller sum
    return [-1, -1]
# Time: O(n), Space: O(1)
\`\`\`

# 2. SLIDING WINDOW: Longest Substring with K Distinct Chars
\`\`\`python
def longest_substring_k_distinct(s, k):
    window_start, max_length = 0, 0
    char_freq = {}
    for window_end in range(len(s)):
        right_char = s[window_end]
        char_freq[right_char] = char_freq.get(right_char, 0) + 1
        while len(char_freq) > k:  # Shrink window
            left_char = s[window_start]
            char_freq[left_char] -= 1
            if char_freq[left_char] == 0:
                del char_freq[left_char]
            window_start += 1
        max_length = max(max_length, window_end - window_start + 1)
    return max_length
# Time: O(n), Space: O(k)
\`\`\`

# 3. MODIFIED BINARY SEARCH: Search in Rotated Array
\`\`\`python
def search_rotated(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        # Left half is sorted
        if arr[left] <= arr[mid]:
            if arr[left] <= target < arr[mid]:
                right = mid - 1
            else:
                left = mid + 1
        # Right half is sorted
        else:
            if arr[mid] < target <= arr[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1
# Time: O(log n), Space: O(1)
\`\`\`

# 4. TOP K ELEMENTS: K Largest Numbers (Min-Heap)
\`\`\`python
import heapq
def find_k_largest(nums, k):
    min_heap = []
    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap)  # Remove smallest
    return list(min_heap)
# Time: O(n log k), Space: O(k)
\`\`\`

# 5. BACKTRACKING: Generate All Subsets
\`\`\`python
def subsets(nums):
    result = []
    def backtrack(start, current):
        result.append(current[:])  # Add copy
        for i in range(start, len(nums)):
            current.append(nums[i])       # Choose
            backtrack(i + 1, current)      # Explore
            current.pop()                  # Un-choose
    backtrack(0, [])
    return result
# Time: O(2^n), Space: O(n) for recursion stack
\`\`\`

Line-by-line walkthrough

  1. 1. Two Pointers: Start at both ends of sorted array. If sum too small, move left up. If too big, move right down. Guaranteed O(n).
  2. 2. Sliding Window: The char_freq dictionary tracks what's in our current window. When too many distinct chars, shrink from left.
  3. 3. The while loop inside the for loop looks like O(n²) but is actually O(n) — each element enters and leaves the window at most once.
  4. 4. Rotated Binary Search: The trick is one half is always sorted. Check if target falls in the sorted half; if yes, search there.
  5. 5. Top K with min-heap: Keep only K elements in the heap. When you add element K+1, the smallest gets evicted. What remains = K largest.
  6. 6. Backtracking for subsets: At each position, you either include the element or skip it. This creates a binary tree of 2^n possibilities.
  7. 7. The pattern of append → recurse → pop is the backtracking template. 'Pop' undoes the choice so you can try the next option.
  8. 8. Notice every solution includes time and space complexity — always state this in interviews.

Spot the bug

# Sliding Window: Find max sum subarray of size K
def max_sum_subarray(arr, k):
    max_sum = 0
    window_sum = 0
    for i in range(len(arr)):
        window_sum += arr[i]
        if i >= k:
            window_sum -= arr[i - k]
            max_sum = max(max_sum, window_sum)
    return max_sum

# Test: max_sum_subarray([2, 1, 5, 1, 3, 2], 3)
# Expected: 9 (5+1+3), but returns 6. Why?
Need a hint?
There are 2 bugs: one is an off-by-one error in when the window becomes valid, and the other is about where the max_sum update happens. When does the first valid window of size K complete?
Show answer
Bug 1: The condition should be 'if i >= k' is correct for removing, but max_sum should also be updated when i == k-1 (the first complete window). Bug 2: max_sum update is inside the 'if i >= k' block, so it misses the first valid window (when i == k-1). Fix: change to 'if i >= k - 1' for the max_sum update, and 'if i >= k' for the subtraction. Or restructure: subtract when i >= k, then always update max_sum when i >= k - 1.

Explain like I'm 5

Think of coding patterns like LEGO instruction booklets. Each booklet teaches you how to build one type of thing — a car, a house, a spaceship. Once you know 15 different booklets, someone can give you a pile of random LEGO pieces and say 'build me a castle with wheels' and you'll think: 'Oh! That's the house booklet + the car booklet combined!' That's pattern recognition!

Fun fact

The 'Two Pointers' technique was first formally described in computer science literature in the 1960s, but it became a standard interview pattern after companies realized it could distinguish between candidates who truly understand algorithms and those who just memorize solutions. The technique alone covers at least 30 common interview questions.

Hands-on challenge

Solve one problem for each of these 5 patterns today: (1) Two Pointers: LeetCode #167 Two Sum II. (2) Sliding Window: LeetCode #3 Longest Substring Without Repeating Characters. (3) BFS: LeetCode #102 Binary Tree Level Order Traversal. (4) Binary Search: LeetCode #33 Search in Rotated Sorted Array. (5) Backtracking: LeetCode #78 Subsets. Before coding each one, write down which pattern you'll use and WHY. Time yourself — aim for under 20 minutes per Easy, 30 minutes per Medium.

More resources

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