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.
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.
left, right = 0, len(arr) - 1
while left < right:
if condition:
left += 1
else:
right -= 1Subarray/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 answerSorted 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 - 1Cycle 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 detectedRange 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]Next 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)Shortest 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)Path 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)Generate 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() # unchooseOverlapping 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]Local 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 backtrackOverlapping 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])Dependency 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)Connected 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 TrueFinding 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 remainMost 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.
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.
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.
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.
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.
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.
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.
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.
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.
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