Skip to content

Pattern Cheatsheet

Every pattern on one page, in study order. Find the signal in the problem statement, pick the pattern from the table, then check its template and the problems that use it.

If the problem says / looks like… Reach for
“Have I seen this before?” or “how many times?”; a nested loop hunting for a matching partner Arrays & Hashing
Sorted input (or you may sort it) and you need a pair or triplet that meets a condition; palindromes Two Pointers
A contiguous subarray or substring; the longest, shortest or best range; “at most k”, “without repeating” Sliding Window
Nested or paired structure (brackets, tags); “next greater / next smaller element” Stack
Sorted or rotated input needing O(log n); smallest value where a yes/no test flips once Binary Search
A singly linked list; the middle, the nth from the end, a cycle, reversal, merging Linked List
A binary tree or BST root; an answer built from left and right subtrees; “level by level” Trees
“k largest”, “k smallest”, “kth”, “top k”; merging sorted streams; a median of growing data Heap
“Return all” subsets, combinations, permutations or paths; small n Backtracking
A grid to flood or count; pairs as dependencies; “connected”, “shortest”, “can all tasks be done?” Graphs
“Prefix”, “autocomplete”, “starts with”; many queries against one word set Tries
A max, min or count of ways; a choice at each step; the answer at i depends on earlier positions 1-D Dynamic Programming
A grid path counted or costed; two strings compared; a state that is a pair (i, j) 2-D Dynamic Programming
A list of ranges (meetings, bookings); merge the overlaps, fit check, or how many at once Intervals

Signal: “Have I seen this before?” or “how many times?”, and a brute force that is a nested loop looking for a partner.

seen = {} # or set(), or collections.Counter()
for i, item in enumerate(items):
key = make_key(item) # the property that defines "a match"
if key in seen: # 1. ask about the past
use(seen[key], i)
seen[key] = i # 2. record the present

Typical complexity: time O(n) for most problems (Group Anagrams O(n·k)); space O(n), or O(1) for Product of Array Except Self.

Problems: Two Sum, Group Anagrams, Top K Frequent Elements, Product of Array Except Self, Longest Consecutive Sequence

Signal: Sorted input (or you may sort it) and you need a pair or triplet meeting a condition; or you are checking a palindrome.

left, right = 0, len(items) - 1
while left < right:
value = measure(items[left], items[right])
if value == goal:
record(left, right)
left += 1
right -= 1
elif value < goal: # need more: move the pointer that raises it
left += 1
else: # need less: move the pointer that lowers it
right -= 1

Typical complexity: time O(n) for most problems (3Sum O(n²)); space O(1), or O(n) for 3Sum.

Problems: Valid Palindrome, Container With Most Water, 3Sum, Trapping Rain Water

Signal: A contiguous subarray or substring, and you want the longest, shortest or best range satisfying a condition.

left = 0
state = {}
best = 0
for right, item in enumerate(items):
add(state, item) # 1. grow
while window_is_invalid(state): # 2. shrink until the rule holds
remove(state, items[left])
left += 1
best = max(best, right - left + 1) # 3. record

Typical complexity: time O(n) (Minimum Window Substring O(m + n)); space O(k) for the character-tracking problems, O(1) for Best Time to Buy and Sell Stock.

Problems: Best Time to Buy and Sell Stock, Longest Substring Without Repeating Characters, Minimum Window Substring

Signal: Nested or paired structure (brackets, tags), or the question “next greater / next smaller element”.

stack = [] # plain LIFO: push openers, pop on closers
for item in items:
if is_opener(item):
stack.append(item)
elif not stack or not matches(stack.pop(), item):
return False
return not stack
stack = [] # monotonic: indices still waiting for an answer
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
j = stack.pop()
answer[j] = i - j
stack.append(i)

Typical complexity: time O(n) per problem (Min Stack O(1) per operation); space O(n).

Problems: Valid Parentheses, Min Stack, Daily Temperatures

Signal: Sorted (or sorted-but-rotated) input needing O(log n), or a monotonic yes/no test where you want the smallest value that passes.

lo, hi = 0, n # hi = n means "none found"
while lo < hi:
mid = lo + (hi - lo) // 2
if ok(mid):
hi = mid # mid might be the answer: keep it
else:
lo = mid + 1
return lo

Typical complexity: time O(log n); space O(1) for both problems.

Problems: Binary Search, Search in Rotated Sorted Array

Signal: A singly linked list with no indexing, where you need the middle, the nth from the end, a cycle, a reversal, or a merge.

# 1. dummy head: the real head is never special; return dummy.next, not head
dummy = ListNode(0, head)
# 2. two pointers, different speeds (or a fixed gap)
slow = fast = dummy
while fast and fast.next:
slow, fast = slow.next, fast.next.next
# 3. in-place reversal
prev, cur = None, head
while cur:
cur.next, prev, cur = prev, cur, cur.next

Typical complexity: time O(n) (Merge Two Sorted Lists O(n + m), LRU Cache O(1) per operation); space O(1), except LRU Cache O(capacity).

Problems: Reverse Linked List, Merge Two Sorted Lists, Linked List Cycle, Remove Nth Node From End of List, LRU Cache

Signal: The input is a binary tree or BST root, and the answer for a node can be built from its left and right subtrees; or the question is level by level.

def dfs(node):
if node is None:
return BASE
left = dfs(node.left) # trust the recursion for each subtree
right = dfs(node.right)
return combine(node, left, right)
def bfs(root):
queue = deque([root] if root else [])
while queue:
for _ in range(len(queue)): # freeze the size: exactly one level
node = queue.popleft()
visit(node)
queue.extend(c for c in (node.left, node.right) if c)

Typical complexity: time O(n) for all problems; space O(h) for the recursive ones, O(n) for Level Order Traversal and Serialize and Deserialize.

Problems: Invert Binary Tree, Maximum Depth of Binary Tree, Binary Tree Level Order Traversal, Validate Binary Search Tree, Lowest Common Ancestor of a Binary Tree, Serialize and Deserialize Binary Tree

Signal: “k largest”, “k smallest”, “kth” or “top k”; merging several sorted lists; or the median of data that keeps arriving.

import heapq
heap = [] # top k: min-heap of size k, root = kth largest
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # evict the smallest
heap = [(src[0], i, 0) for i, src in enumerate(sources) if src] # k-way merge
heapq.heapify(heap)
while heap:
val, i, j = heapq.heappop(heap)
if j + 1 < len(sources[i]):
heapq.heappush(heap, (sources[i][j + 1], i, j + 1))

Typical complexity: Kth Largest O(n log k) time, O(k) space; Merge k Sorted Lists O(N log k) time, O(k) space; Find Median from Data Stream O(log n) per add, O(1) per median, O(n) space.

Problems: Kth Largest Element in an Array, Merge k Sorted Lists, Find Median from Data Stream

Signal: “Return all” subsets, combinations, permutations or paths, on small input (n around 10 to 20).

res, path = [], []
def backtrack(start):
if is_complete(path):
res.append(path[:]) # copy! path keeps changing
return
for i in range(start, len(nums)):
if not valid(nums[i]): # prune dead branches early
continue
path.append(nums[i]) # choose
backtrack(i + 1) # explore
path.pop() # un-choose
backtrack(0)
return res

Typical complexity: exponential, time only: Subsets O(n · 2^n), Permutations O(n · n!), Combination Sum O(N^(T/M)), Word Search O(m · n · 3^L).

Problems: Subsets, Combination Sum, Permutations, Word Search

Signal: A grid to flood or count regions, a list of pairs as dependencies, or “shortest” / “levels” (BFS); “can all tasks be done?” means topological sort.

from collections import deque
def bfs(starts):
seen = set(starts) # mark when ENQUEUED, not when popped
queue = deque(starts) # several starts = multi-source BFS
level = 0
while queue:
for _ in range(len(queue)): # one pass = one level
node = queue.popleft()
for nxt in graph[node]: # grid: the 4 in-bounds neighbors
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
level += 1

Typical complexity: time O(V + E) for graph problems, O(m·n) for grid problems; space O(V), O(V + E), or O(m·n).

Problems: Number of Islands, Clone Graph, Course Schedule, Rotting Oranges

Signal: The problem says “prefix”, “autocomplete” or “starts with”, or you answer many queries against one fixed set of words.

class Node:
def __init__(self):
self.children = {} # char -> Node
self.is_word = False
def walk(root, s):
node = root
for ch in s:
if ch not in node.children:
return None # no stored word goes this way
node = node.children[ch]
return node # check node.is_word for a full word

Typical complexity: time O(L) per operation; space O(total chars).

Problems: Implement Trie (Prefix Tree)

Signal: The question asks for a maximum, minimum or count of ways; each step is a choice; the same sub-question repeats.

# if dp[i] reads only the last two values, keep two variables instead
def solve(nums):
n = len(nums)
dp = [0] * (n + 1) # dp[i] = answer for the first i items
dp[0] = BASE # base case(s)
for i in range(1, n + 1):
dp[i] = combine(dp[i - 1], ...) # recurrence: from earlier states
return dp[n]

Typical complexity: time O(n) for Climbing Stairs, House Robber and Maximum Subarray; O(n log n) for Longest Increasing Subsequence; O(amount × coins) for Coin Change; O(n³) for Word Break.

Problems: Climbing Stairs, House Robber, Maximum Subarray, Coin Change, Word Break, Longest Increasing Subsequence

Signal: A grid where you count paths or optimize a cost moving right and down, or two strings you compare; the state is a pair (i, j).

dp = [[0] * (n + 1) for _ in range(m + 1)] # extra row/col = empty-prefix base case
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = combine(dp[i - 1][j], # from above
dp[i][j - 1], # from left
dp[i - 1][j - 1]) # from diagonal
return dp[m][n]

Typical complexity: time O(m * n) for both; space O(m * n), or O(n) for Unique Paths.

Problems: Unique Paths, Longest Common Subsequence

Signal: A list of ranges (meetings, bookings, segments); merge the overlaps, check whether they all fit, or count how many overlap at once. Sort by start first.

intervals.sort() # sort by start
merged = []
for start, end in intervals:
if merged and start <= merged[-1][1]: # overlaps the last merged range
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
# how many overlap at once: sorted starts vs sorted ends
starts, ends = sorted(s for s, e in intervals), sorted(e for s, e in intervals)
rooms = e = 0
for s in starts:
if s < ends[e]: rooms += 1 # still busy: need another
else: e += 1 # one finished: reuse

Typical complexity: time O(n log n) for both problems (the sort); space O(n).

Problems: Merge Intervals, Meeting Rooms II