Skip to main content

LeetCode Patterns Every Student Should Know (2026 Guide)

LeetCode Patterns Every Student Should Know (2026 Guide)

If you are grinding LeetCode by solving 500 random problems, you are doing it the hard way.

The secret to cracking Big Tech coding interviews isn't memorization—it's pattern recognition. After solving enough problems, you'll notice that many interview questions are variations of the same core techniques. If you learn the underlying pattern, you can solve hundreds of problems you've never seen before.

💡 The Template Mindset: Every pattern has a reusable template. Instead of memorizing complete solutions, memorize the control flow. Once you recognize the pattern, you can adapt the template to the problem.

Here are the absolute, non-negotiable LeetCode patterns every student must know before stepping into a technical interview.


Quick Reference: Time & Space Complexity

Pattern Time Space
Two Pointers $O(n)$ $O(1)$
Sliding Window $O(n)$ $O(1)$
Binary Search $O(\log n)$ $O(1)$
Merge Intervals $O(n \log n)$ $O(n)$
Monotonic Stack $O(n)$ $O(n)$
BFS $O(V + E)$ $O(V)$
Heap / Priority Queue $O(n \log k)$ $O(k)$
Backtracking (DFS) Exponential $O(\text{depth})$

⭐ Beginner Patterns

Start here. These patterns form the foundation of array and string manipulation.

Pattern 1: Two Pointers

Time: $O(n)$ | Space: $O(1)$

The Concept: Place two pointers (indices) on an array or string. They can start at opposite ends and move inward, or start together and move at different speeds.

Interview Signals (When to use): * The array is sorted. * You need to find pairs, triplets, or palindromes. * Removing duplicates in-place.

Classic Problems: * Two Sum II - Input Array Is Sorted (Easy) * Container With Most Water (Medium) * 3Sum (Medium)

The Template:

def two_sum_sorted(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  # We need a bigger sum
        else:
            right -= 1 # We need a smaller sum
    return []

Pattern 2: Sliding Window

Time: $O(n)$ | Space: $O(1)$

The Concept: Instead of recalculating the sum or state of a subarray from scratch every time, you maintain a "window" of elements. As you move the window forward by one element, you add the new element and remove the oldest one.

Interview Signals (When to use): * "Longest substring", "Shortest subarray", "Maximum consecutive". * Dealing with contiguous sequences. * Fixed-size or dynamic window constraints.

Classic Problems: * Maximum Average Subarray I (Easy) * Longest Substring Without Repeating Characters (Medium) * Best Time to Buy and Sell Stock (Easy)

The Template:

def max_subarray_sum(arr, k):
    window_sum = sum(arr[:k])
    max_sum = window_sum

    for i in range(k, len(arr)):
        # Add the new element, subtract the oldest element
        window_sum += arr[i] - arr[i - k]
        max_sum = max(max_sum, window_sum)

    return max_sum

Pattern 3: Modified Binary Search

Time: $O(\log n)$ | Space: $O(1)$

The Concept: Standard binary search looks for an exact match. Modified binary search looks for the boundary where a condition becomes true or false.

Interview Signals (When to use): * The array is sorted, but possibly rotated (e.g., [4,5,6,1,2,3]). * Finding the first/last occurrence of an element. * "Find the minimum" in a sorted array.

Classic Problems: * Find Minimum in Rotated Sorted Array (Medium) * Koko Eating Bananas (Medium)


⭐⭐ Intermediate Patterns

These patterns introduce scheduling, overlapping ranges, and stack-based logic.

Pattern 4: Merge Intervals

Time: $O(n \log n)$ | Space: $O(n)$

The Concept: Problems give you intervals like [start, end]. The trick is to sort the intervals by their start time first, then iterate through and merge or check for overlaps.

Interview Signals (When to use): * Ranges, schedules, or time slots. * "Find overlapping time" or "merge ranges".

Classic Problems: * Merge Intervals (Medium) * Meeting Rooms II (Medium)

Pattern 5: Fast & Slow Pointers (Tortoise & Hare)

Time: $O(n)$ | Space: $O(1)$

The Concept: Two pointers move through a Linked List or Array. The "slow" pointer moves one step at a time, while the "fast" pointer moves two steps.

Interview Signals (When to use): * Find the middle of a Linked List. * Detect a cycle. * Find a duplicate number without modifying the array.

Pattern 6: Monotonic Stack

Time: $O(n)$ | Space: $O(n)$

The Concept: You use a stack to keep track of elements in a specific order (usually decreasing or increasing). When a new element arrives, you pop elements from the stack that violate the order, processing them before pushing the new element.

Interview Signals (When to use): * "Next greater element" or "Next smaller element". * "Span of days" (e.g., stock spans). * Calculating area of rectangles in a histogram.

Classic Problems: * Daily Temperatures (Medium) * Next Greater Element I (Easy) * Largest Rectangle in Histogram (Hard)

The Template (Next Greater Element):

def next_greater_element(nums):
    result = [-1] * len(nums)
    stack = [] # Stores indices

    for i in range(len(nums)):
        # While stack is not empty and current element is greater 
        # than the element at the index on top of the stack
        while stack and nums[i] > nums[stack[-1]]:
            index = stack.pop()
            result[index] = nums[i]
        stack.append(i)

    return result

⭐⭐⭐ Advanced Patterns

These patterns involve graph traversal, priority ordering, and exhaustive search.

Pattern 7: Breadth-First Search (BFS) on a Matrix

Time: $O(V + E)$ | Space: $O(V)$

The Concept: When traversing a 2D grid (like a maze or map), BFS uses a Queue to explore neighbors level-by-level. This guarantees the shortest path in an unweighted grid.

Interview Signals (When to use): * "Minimum steps" or "Shortest path". * "Level order" traversal. * Spread infection / rotting oranges.

Classic Problems: * Rotting Oranges (Medium) * 01 Matrix (Medium)

The Template:

from collections import deque

def bfs_matrix(grid):
    rows, cols = len(grid), len(grid[0])
    queue = deque()
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Right, Down, Left, Up

    while queue:
        r, c = queue.popleft()
        for dr, dc in directions:
            new_r, new_c = r + dr, c + dc
            if 0 <= new_r < rows and 0 <= new_c < cols:
                # Process neighbor and add to queue
                pass

Pattern 8: Heap / Priority Queue

Time: $O(n \log k)$ | Space: $O(k)$

The Concept: A Heap is a specialized tree-based structure. A Min-Heap keeps the smallest element at the top; a Max-Heap keeps the largest. It's perfect for dynamically tracking the "Top K" elements without sorting the whole array.

Interview Signals (When to use): * "Top K", "K closest", "Kth largest/smallest". * Merging K sorted lists. * Continuously tracking the median of a stream.

Classic Problems: * Top K Frequent Elements (Medium) * K Closest Points to Origin (Medium) * Merge K Sorted Lists (Hard)

Pattern 9: Subsets / Backtracking (DFS)

Time: Exponential | Space: $O(\text{depth})$

The Concept: You need to explore all possible combinations, permutations, or arrangements. You build a recursive tree, adding an element, making a recursive call, and then removing that element (backtracking) to explore the next path.

Interview Signals (When to use): * "Generate all..." or "Find all combinations/permutations". * Solving puzzles (Sudoku, N-Queens).

Classic Problems: * Subsets (Medium) * Permutations (Medium) * Combination Sum (Medium)

The Template:

def subsets(nums):
    result = []

    def backtrack(index, current_subset):
        result.append(current_subset[:])

        for i in range(index, len(nums)):
            current_subset.append(nums[i])
            backtrack(i + 1, current_subset)
            current_subset.pop() # Backtrack

    backtrack(0, [])
    return result

⚠️ Note on Dynamic Programming (DP): DP is conspicuously absent from this list. That is because DP deserves its own guide—it's an entire family of patterns rather than a single technique. Once you master the 9 patterns above, move on to DP, followed by Tries, Union Find, and Graph algorithms.


The "What is this problem?" Flowchart

When you read a problem, run through this mental checklist to identify the pattern:

graph TD
    A[Read Problem] --> B{Is it a Tree or Graph?}
    B -->|Yes| C{Need shortest path?}
    C -->|Yes| D[Pattern: BFS]
    C -->|No| E[Pattern: DFS / Backtracking]

    B -->|No| F{Is it an Array/String?}
    F -->|Yes| G{Need contiguous subarray?}
    G -->|Yes| H[Pattern: Sliding Window]
    G -->|No| I{Is it sorted?}
    I -->|Yes| J[Pattern: Two Pointers / Binary Search]
    I -->|No| K{Need combinations/permutations?}
    K -->|Yes| E

    style D fill:#4CAF50,color:#fff
    style H fill:#2196F3,color:#fff
    style J fill:#ff9,stroke:#333
    style E fill:#9c27b0,color:#fff

A 4-Week Study Roadmap

Don't try to learn all 9 patterns in a weekend. Space them out to build muscle memory.

  • Week 1: The Basics
    • ✅ Two Pointers (5 problems)
    • ✅ Sliding Window (5 problems)
  • Week 2: Search & Schedules
    • ✅ Modified Binary Search (5 problems)
    • ✅ Merge Intervals (5 problems)
  • Week 3: Stacks & Graphs
    • ✅ Monotonic Stack (5 problems)
    • ✅ BFS on Matrix (5 problems)
  • Week 4: Priorities & Combinations
    • ✅ Heap / Priority Queue (5 problems)
    • ✅ Backtracking / DFS (5 problems)

How to Actually Study

  1. Don't look at the solution immediately. Spend exactly 30 minutes trying to solve a new problem. If you fail, look at the solution, understand the pattern, code it up yourself, and try it again the next day.
  2. Group by Pattern, not by Difficulty. Don't do 10 random "Easy" problems. Do 10 "Sliding Window" problems back-to-back until the template is muscle memory.
  3. Space your repetition. If you solve "Merge Intervals" on Monday, do it again on Thursday, and again next month. Spaced repetition is how patterns move from short-term memory to long-term intuition.

Don't let LeetCode intimidate you. It’s not an IQ test; it’s a pattern recognition test. Learn the patterns, and you'll be able to decode almost any problem they throw at you.

Related Articles