Study Guide

LeetCode Patterns

Your LeetCode patterns cheat sheet with the 15 coding patterns that solve 90% of interview problems. Each pattern includes when to use it, a code template, and 79 curated LeetCode problems patterns to practice. Learn the pattern, not the problem.

15 patterns79 problemsCode templates in Python
0 / 79 problems
Easy Medium Hard
swap_horiz

Two Pointers

6 problems

Sorted arrays, pair/triplet sums, removing duplicates, palindromes, partitioning. Use when you need to compare elements from both ends or walk two references through a sequence.

codeTemplate
left, right = 0, len(arr) - 1
while left < right:
    if condition:
        left += 1
    else:
        right -= 1
Two Sum IIMedium
Valid PalindromeEasy
3SumMedium
Container With Most WaterMedium
Trapping Rain WaterHard
Remove Duplicates from Sorted ArrayEasy
width

Sliding Window

6 problems

Subarray/substring problems with a contiguous window. Max/min in a window, longest substring without repeats, anagram search. Optimizes brute-force O(n²) to O(n).

codeTemplate
left = 0
for right in range(len(arr)):
    # expand window
    while window_invalid:
        # shrink from left
        left += 1
    # update best answer
Best Time to Buy and Sell StockEasy
Longest Substring Without Repeating CharactersMedium
Longest Repeating Character ReplacementMedium
Minimum Window SubstringHard
Sliding Window MaximumHard
Permutation in StringMedium
search

Binary Search

6 problems

Sorted input, monotonic condition, minimize/maximize an answer. Halves the search space each step → O(log n). Also works on answer space (binary search on answer).

codeTemplate
lo, hi = 0, len(arr) - 1
while lo <= hi:
    mid = (lo + hi) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        lo = mid + 1
    else:
        hi = mid - 1
Binary SearchEasy
Search in Rotated Sorted ArrayMedium
Find Minimum in Rotated Sorted ArrayMedium
Koko Eating BananasMedium
Median of Two Sorted ArraysHard
Search a 2D MatrixMedium
speed

Fast & Slow Pointers

5 problems

Cycle detection in linked lists, finding the middle node, detecting loops in sequences. Slow moves 1 step, fast moves 2 — they meet inside a cycle.

codeTemplate
slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    if slow == fast:
        # cycle detected
Linked List CycleEasy
Middle of the Linked ListEasy
Linked List Cycle IIMedium
Happy NumberEasy
Find the Duplicate NumberMedium
functions

Prefix Sum

5 problems

Range sum queries, subarray sum equals K, equilibrium index. Build prefix array in O(n), answer any range query in O(1). Often paired with hash maps.

codeTemplate
prefix = [0] * (len(arr) + 1)
for i in range(len(arr)):
    prefix[i+1] = prefix[i] + arr[i]
# sum(arr[l:r]) = prefix[r] - prefix[l]
Range Sum Query - ImmutableEasy
Subarray Sum Equals KMedium
Product of Array Except SelfMedium
Contiguous ArrayMedium
Path Sum IIIMedium
stacked_bar_chart

Monotonic Stack

5 problems

Next greater/smaller element, largest rectangle in histogram, stock span, daily temperatures. Stack maintains increasing or decreasing order.

codeTemplate
stack = []
for i, val in enumerate(arr):
    while stack and arr[stack[-1]] < val:
        idx = stack.pop()
        # arr[idx]'s next greater = val
    stack.append(i)
Daily TemperaturesMedium
Next Greater Element IEasy
Largest Rectangle in HistogramHard
Online Stock SpanMedium
Trapping Rain WaterHard
account_tree

BFS (Breadth-First Search)

6 problems

Shortest path in unweighted graphs, level-order tree traversal, minimum steps/moves, nearest neighbor. Explores level by level using a queue.

codeTemplate
from collections import deque
queue = deque([start])
visited = {start}
while queue:
    node = queue.popleft()
    for neighbor in graph[node]:
        if neighbor not in visited:
            visited.add(neighbor)
            queue.append(neighbor)
Binary Tree Level Order TraversalMedium
Number of IslandsMedium
Rotting OrangesMedium
Word LadderHard
Open the LockMedium
Shortest Path in Binary MatrixMedium
explore

DFS (Depth-First Search)

6 problems

Path finding, tree traversals (pre/in/post-order), cycle detection, connected components, island counting. Goes deep before backtracking.

codeTemplate
def dfs(node, visited):
    if node in visited:
        return
    visited.add(node)
    for neighbor in graph[node]:
        dfs(neighbor, visited)
Maximum Depth of Binary TreeEasy
Number of IslandsMedium
Clone GraphMedium
Course ScheduleMedium
Pacific Atlantic Water FlowMedium
Path SumEasy
undo

Backtracking

6 problems

Generate all combinations, permutations, subsets, N-queens, Sudoku, word search. Systematically explore all candidates and prune invalid paths early.

codeTemplate
def backtrack(path, choices):
    if is_solution(path):
        result.append(path[:])
        return
    for choice in choices:
        path.append(choice)    # choose
        backtrack(path, ...)   # explore
        path.pop()             # unchoose
SubsetsMedium
PermutationsMedium
Combination SumMedium
Word SearchMedium
N-QueensHard
Palindrome PartitioningMedium
grid_on

Dynamic Programming

7 problems

Overlapping subproblems + optimal substructure. Sequences (LIS, LCS), knapsack, path counting, string matching. Top-down (memoization) or bottom-up (tabulation).

codeTemplate
# Bottom-up
dp = [base_case] * (n + 1)
for i in range(1, n + 1):
    dp[i] = recurrence(dp[i-1], ...)
return dp[n]
Climbing StairsEasy
House RobberMedium
Longest Increasing SubsequenceMedium
Coin ChangeMedium
Unique PathsMedium
Edit DistanceHard
Longest Common SubsequenceMedium
bolt

Greedy

5 problems

Local optimal choice leads to global optimal. Interval scheduling, activity selection, jump game, task assignment. Usually requires sorting first.

codeTemplate
# Sort by end time / weight / ratio
items.sort(key=lambda x: x.end)
for item in items:
    if can_take(item):
        take(item)  # never backtrack
Jump GameMedium
Jump Game IIMedium
Gas StationMedium
Task SchedulerMedium
Partition LabelsMedium
merge

Merge Intervals

5 problems

Overlapping intervals, meeting rooms, insert interval, interval intersection. Sort by start time, then merge/compare adjacent pairs.

codeTemplate
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
    if start <= merged[-1][1]:
        merged[-1][1] = max(merged[-1][1], end)
    else:
        merged.append([start, end])
Merge IntervalsMedium
Insert IntervalMedium
Non-overlapping IntervalsMedium
Meeting Rooms IIMedium
Interval List IntersectionsMedium
linear_scale

Topological Sort

4 problems

Dependency ordering in DAGs. Course prerequisites, build order, task scheduling. Use Kahn's (BFS with indegree) or DFS post-order.

codeTemplate
# Kahn's algorithm (BFS)
indegree = {u: 0 for u in graph}
for u in graph:
    for v in graph[u]:
        indegree[v] += 1
queue = deque(u for u in indegree if indegree[u] == 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)
Course ScheduleMedium
Course Schedule IIMedium
Alien DictionaryHard
Minimum Height TreesMedium
group_work

Union-Find

5 problems

Connected components, cycle detection in undirected graphs, accounts merge, redundant connection. Near O(1) per operation with path compression + rank.

codeTemplate
parent = list(range(n))
rank = [0] * n
def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])  # path compression
    return parent[x]
def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb: return False
    if rank[ra] < rank[rb]: ra, rb = rb, ra
    parent[rb] = ra
    if rank[ra] == rank[rb]: rank[ra] += 1
    return True
Number of Connected ComponentsMedium
Redundant ConnectionMedium
Accounts MergeMedium
Longest Consecutive SequenceMedium
Graph Valid TreeMedium
filter_list

Heap / Top-K

6 problems

Finding K largest/smallest elements, merge K sorted lists, running median, priority-based scheduling. Use min-heap for top-K largest, max-heap for top-K smallest.

codeTemplate
import heapq
# Top K largest
heap = []
for num in arr:
    heapq.heappush(heap, num)
    if len(heap) > k:
        heapq.heappop(heap)  # remove smallest
return heap  # k largest remain
Kth Largest Element in an ArrayMedium
Top K Frequent ElementsMedium
Merge k Sorted ListsHard
Find Median from Data StreamHard
K Closest Points to OriginMedium
Task SchedulerMedium

Why learn LeetCode patterns?

Most people approach LeetCode wrong. They grind hundreds of random problems hoping to memorize enough to pass an interview. The pattern-based approach is fundamentally different: you learn 15 reusable strategies that apply to entire categories of problems.

When you see a new problem in an interview, you don't need to have seen it before. You recognize which LeetCode pattern applies (sliding window? two pointers? BFS?) and adapt the template. This is how top performers approach coding interviews, and why a LeetCode patterns cheat sheet is so valuable to have on hand.

This page organizes 79 carefully selected LeetCode problems patterns across 15 categories. Each pattern includes a clear explanation of when to use it, a Python code template you can adapt, and problems ordered from easy to hard. Track your progress with checkboxes as you work through each pattern.

Frequently asked questions

What are LeetCode patterns?expand_more

LeetCode patterns are reusable problem-solving strategies that apply to entire categories of coding interview questions. Instead of memorizing hundreds of individual solutions, you learn 15 patterns (like sliding window, two pointers, BFS/DFS) that can be adapted to solve most problems you encounter. Candidates who recognize patterns have an 85% success rate compared to 35% for those who don't.

Is there a LeetCode patterns cheat sheet?expand_more

Yes, this page serves as a complete LeetCode patterns cheat sheet. It covers all 15 core coding patterns with a one-line summary of when to use each, a Python code template, and 5-8 curated practice problems per pattern. Bookmark it and use it as a quick reference during your interview prep.

How many LeetCode patterns are there?expand_more

While different sources list between 12 and 25 patterns, there are roughly 15 core patterns that cover 90% of coding interview questions: Two Pointers, Sliding Window, Binary Search, Fast & Slow Pointers, Prefix Sum, Monotonic Stack, BFS, DFS, Backtracking, Dynamic Programming, Greedy, Merge Intervals, Topological Sort, Union-Find, and Heap/Top-K.

What are LeetCode problems patterns?expand_more

LeetCode problems patterns refer to the recurring structures behind interview questions. For example, any problem asking for the shortest path in an unweighted graph follows the BFS pattern. Any problem about finding a contiguous subarray that meets a condition follows the sliding window pattern. Once you recognize these LeetCode problems patterns, you can solve new questions you have never seen before.

What order should I learn LeetCode patterns?expand_more

Start with Two Pointers and Sliding Window since they are the most intuitive and appear frequently. Then learn Binary Search, BFS/DFS, and Prefix Sum. Once comfortable, move to Backtracking, Dynamic Programming, and Greedy. Finally, tackle specialized patterns like Monotonic Stack, Topological Sort, and Union-Find. This page lists patterns roughly in this recommended order.

How many problems should I solve per pattern?expand_more

Aim for 5-8 problems per pattern. Start with 1-2 easy problems to internalize the template, then do 2-3 medium problems to see variations, and finally 1-2 hard problems to push your understanding. That is roughly 75-120 problems total across all 15 patterns, which is far more effective than solving 300 random problems.

Are LeetCode patterns better than Blind 75?expand_more

They complement each other. Blind 75 is a curated set of specific problems. LeetCode patterns teach you the strategies to solve those problems and any new ones you have not seen before. Learn the patterns first for the frameworks, then use Blind 75 or Grind 75 as practice to reinforce them.

How long does it take to learn all LeetCode patterns?expand_more

Most people can learn all 15 patterns in 4-8 weeks with consistent daily practice. Spend 2-3 days per pattern: day 1 studying the template and solving 2 easy problems, day 2-3 solving medium and hard problems. Revisit patterns you found difficult after finishing the full cycle.

Practice patterns with a real interviewer

Crackr's AI interviewer tests whether you can recognize and apply the right pattern under pressure, just like a real coding interview.

Try Crackr freearrow_forward

Continue learning