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.
Two Pointers
6 problemsSorted 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.
left, right = 0, len(arr) - 1
while left < right:
if condition:
left += 1
else:
right -= 1Sliding Window
6 problemsSubarray/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).
left = 0
for right in range(len(arr)):
# expand window
while window_invalid:
# shrink from left
left += 1
# update best answerBinary Search
6 problemsSorted 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).
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 - 1Fast & Slow Pointers
5 problemsCycle detection in linked lists, finding the middle node, detecting loops in sequences. Slow moves 1 step, fast moves 2 — they meet inside a cycle.
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# cycle detectedPrefix Sum
5 problemsRange 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.
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]Monotonic Stack
5 problemsNext greater/smaller element, largest rectangle in histogram, stock span, daily temperatures. Stack maintains increasing or decreasing order.
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)BFS (Breadth-First Search)
6 problemsShortest path in unweighted graphs, level-order tree traversal, minimum steps/moves, nearest neighbor. Explores level by level using a queue.
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)DFS (Depth-First Search)
6 problemsPath finding, tree traversals (pre/in/post-order), cycle detection, connected components, island counting. Goes deep before backtracking.
def dfs(node, visited):
if node in visited:
return
visited.add(node)
for neighbor in graph[node]:
dfs(neighbor, visited)Backtracking
6 problemsGenerate all combinations, permutations, subsets, N-queens, Sudoku, word search. Systematically explore all candidates and prune invalid paths early.
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() # unchooseDynamic Programming
7 problemsOverlapping subproblems + optimal substructure. Sequences (LIS, LCS), knapsack, path counting, string matching. Top-down (memoization) or bottom-up (tabulation).
# Bottom-up
dp = [base_case] * (n + 1)
for i in range(1, n + 1):
dp[i] = recurrence(dp[i-1], ...)
return dp[n]Greedy
5 problemsLocal optimal choice leads to global optimal. Interval scheduling, activity selection, jump game, task assignment. Usually requires sorting first.
# Sort by end time / weight / ratio
items.sort(key=lambda x: x.end)
for item in items:
if can_take(item):
take(item) # never backtrackMerge Intervals
5 problemsOverlapping intervals, meeting rooms, insert interval, interval intersection. Sort by start time, then merge/compare adjacent pairs.
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])Topological Sort
4 problemsDependency ordering in DAGs. Course prerequisites, build order, task scheduling. Use Kahn's (BFS with indegree) or DFS post-order.
# 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)Union-Find
5 problemsConnected components, cycle detection in undirected graphs, accounts merge, redundant connection. Near O(1) per operation with path compression + rank.
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 TrueHeap / Top-K
6 problemsFinding 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.
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 remainWhy 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?add
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?add
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?add
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?add
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?add
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?add
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?add
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?add
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_forwardContinue learning
Blind 75
The original 75 LeetCode problems
DSA Tracker
177 problems across 16 DSA topics
Grind 75
Updated plan with custom time targets
NeetCode 150
Expanded set covering all patterns
Big O Cheat Sheet
Time & space complexity reference
Algorithm Visualizers
See data structures in action
Company Questions
Real interview questions by company
Java Interview Questions
1,715 questions ranked by frequency