LeetCode Top 100 Pattern Roadmap
Owner: cassie Goal: finish the full list by pattern, in a clean learning order Method: learn pattern -> memorize recognition signals -> use template -> solve grouped problems
Pattern Summary
This roadmap teaches one core interview skill: classify first, code second. The goal is not to memorize 100 separate solutions, but to learn the recognition signals behind common patterns such as hashing, two pointers, sliding window, recursion, BFS/DFS, heap, and dynamic programming.
Problem Meaning
This page is a learning roadmap rather than a single problem statement. To make the roadmap concrete, the representative code below uses Two Sum, because it is one of the cleanest examples of “see a signal, pick a pattern, apply a template.”
Python Code
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen: dict[int, int] = {}
for index, value in enumerate(nums):
need = target - value
if need in seen:
return [seen[need], index]
seen[value] = index
return []
print(Solution().twoSum([2, 7, 11, 15], 9))
Time Complexity
The representative solution scans the array once and uses constant-time hash lookups on average, so the time complexity is O(n).
Space Complexity
The hash map may store up to n elements, so the space complexity is O(n).
How To Think About It
The most important habit is to translate the wording into a pattern signal. Two Sum says “find a complement quickly,” which is a hash map signal. Once you notice that, the code is almost predetermined: for each number, check whether its complement has appeared before. This roadmap tries to build that recognition habit across the whole interview set.
Example Case
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: when we reach 7, we already saw 2, and 2 + 7 = 9.
Edge case: if no pair exists, the sample implementation returns []; some interview versions guarantee that one answer always exists.
Common Follow-up Questions
- If the array is sorted, when should you switch from hash map to two pointers?
- If the question asks for all triplets summing to zero, how does the pattern change into
3Sum? - If the target involves a continuous subarray instead of two values, when should you think about prefix sum or sliding window?
How To Use This Document
For every problem, do this in order:
// Step 1: classify the problem
// array? string? linked list? tree? graph? matrix?
// Step 2: identify the pattern
// hash? two pointers? sliding window? binary search?
// stack? backtracking? BFS/DFS? heap? DP?
// Step 3: state the core invariant before coding
// what does each pointer mean?
// what does dp[i] / dp[i][j] mean?
// what does the recursive function return?
// Step 4: hand-simulate a small example
// verify variable updates before writing code
Golden rule:
// Do not memorize problem titles.
// Memorize recognition signals + solution templates.
Suggested Learning Order
- Arrays / Hashing / Basic scanning
- Two pointers
- Linked lists
- Stack / Monotonic stack
- Binary trees / BST
- Binary search
- Sliding window
- Backtracking
- Graph BFS / DFS
- Heap / Priority queue
- Dynamic programming
- Hard mixed problems
Reason:
// First build manipulation skills
// Then build pattern recognition
// Then build state-design ability for DP / hard problems
Pattern 1: Arrays / Hashing / Basic Scanning
Recognition Signals
// "find if exists" / "count frequency" / "seen before"
=> think hash map / hash set
// "subarray sum" / "prefix relation"
=> think prefix sum + hash map
// "missing / duplicate / range 1..n"
=> think index mapping / in-place tricks / Floyd
// "best profit" / "maximum subarray" / "scan once"
=> think running state while traversing
Core Templates
// Hash lookup template
for x in nums:
// check what you need first
// then record current info
// Prefix sum + hashmap
prefix = 0
count[0] = 1
for x in nums:
prefix += x
// if prefix - k appeared before,
// that previous position forms a valid subarray
ans += count[prefix - k]
count[prefix] += 1
// One-pass best state
for x in nums:
// maintain "best so far"
// update answer using current value + historical info
Learning Order
- Two Sum
- Majority Element
- Single Number
- Best Time to Buy and Sell Stock
- Maximum Subarray
- Move Zeroes
- Rotate Array
- Product of Array Except Self
- Group Anagrams
- Longest Consecutive Sequence
- Subarray Sum Equals K
- Merge Intervals
- Sort Colors
- Find the Duplicate Number
- First Missing Positive
- Next Permutation
Problem Notes
Two Sum// store value -> index // before inserting current value, check whether target - x already existsMajority Element// Boyer-Moore voting // maintain a candidate and a counter // same value => counter++ // different value => counter--Single Number// XOR property: // a ^ a = 0 // a ^ 0 = a // duplicates cancel outBest Time to Buy and Sell Stock// maintain the minimum price seen so far // profit at day i = price[i] - min_priceMaximum Subarray// Kadane's algorithm // current best ending here: // either extend previous subarray or restart at current numberProduct of Array Except Self// prefix product from left // suffix product from right // answer[i] = left product * right productGroup Anagrams// same sorted string => same group // key can be sorted(word) or 26-count tupleLongest Consecutive Sequence// put all numbers into a set // only start counting from numbers whose predecessor does not existSubarray Sum Equals K// prefix sum difference // count how many previous prefixes equal current_prefix - kMerge Intervals// interval problems almost always start with sorting by start // merge if current.start <= last.endSort Colors// Dutch National Flag // maintain boundaries for 0-region and 2-regionFind the Duplicate Number// values behave like next pointers // use Floyd cycle detectionFirst Missing Positive// put each valid value x into index x - 1 // then scan for first mismatchNext Permutation// from right, find first descending pivot // swap with next larger element on the right // reverse the suffix
Common Mistakes
- Using sorting when the problem requires original index
- Forgetting to initialize prefix hash with
0 -> 1 - Confusing subarray with subsequence
- Writing an
O(n^2)scan when a hash or single pass is enough
Pattern 2: Two Pointers
Recognition Signals
// sorted array
// opposite ends moving inward
// remove / compact in-place
// palindrome / pair sum / triplets
// linked list slow-fast behavior
Core Templates
// opposite-direction pointers
left = 0
right = n - 1
while left < right:
// update answer
// move the side that cannot help more
// slow-fast pointers
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
Learning Order
- Move Zeroes
- Container With Most Water
- 3Sum
- Trapping Rain Water
- Linked List Cycle
- Linked List Cycle II
- Palindrome Linked List
Problem Notes
Move Zeroes// slow pointer = next position to place a non-zero // fast pointer scans every elementContainer With Most Water// area depends on shorter side // move the shorter side because the taller side is not the bottleneck3Sum// sort first // fix one number, then solve two-sum with left/right pointers // skip duplicates carefullyTrapping Rain Water// water at each side depends on smaller max boundary // maintain left_max and right_maxLinked List Cycle// if slow and fast meet, there is a cycleLinked List Cycle II// after slow meets fast, // reset one pointer to head // move both one step at a time // their next meeting point is the cycle entrance
Pattern 3: Linked Lists
Recognition Signals
// reverse / merge / delete / swap
// nth from end
// middle of list
// cycle or intersection
Core Templates
// dummy node for deletion / insertion / swap
dummy.next = head
prev = dummy
// reverse a list
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
// merge two sorted lists
dummy = ListNode(0)
tail = dummy
while l1 and l2:
// append smaller node
// append remainder
Learning Order
- Reverse Linked List
- Merge Two Sorted Lists
- Remove Nth Node From End of List
- Add Two Numbers
- Intersection of Two Linked Lists
- Swap Nodes in Pairs
- Copy List with Random Pointer
- Sort List
- LRU Cache
- Merge k Sorted Lists
- Reverse Nodes in k-Group
Problem Notes
Remove Nth Node From End of List// move fast pointer n steps first // then move slow and fast together // slow stops right before node to deleteAdd Two Numbers// digit-by-digit simulation with carry // keep going while l1 or l2 or carry existsIntersection of Two Linked Lists// pointer A goes A->B // pointer B goes B->A // equalized path lengths make them meetCopy List with Random Pointer// either hashmap old->new // or interleave copied nodes between original nodesSort List// linked list merge sort // split by middle, sort recursively, mergeLRU Cache// hashmap for O(1) lookup // doubly linked list for O(1) remove / move-to-frontReverse Nodes in k-Group// identify a block of k nodes // reverse that block // reconnect to previous and next parts
Pattern 4: Stack / Monotonic Stack
Recognition Signals
// matching pairs
// nested expressions
// nearest greater / smaller
// histogram / temperatures / waiting days
Core Templates
// standard stack
for ch in s:
// push opening info
// on closing symbol, pop and validate
// monotonic stack usually stores indices
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
idx = stack.pop()
// current i is the next greater element for idx
stack.append(i)
Learning Order
- Valid Parentheses
- Min Stack
- Decode String
- Daily Temperatures
- Largest Rectangle in Histogram
- Longest Valid Parentheses
Problem Notes
Min Stack// either keep a second stack of minima // or store pairs: (value, current_min)Decode String// push previous string and repeat count when seeing '[' // build current segment until ']'Daily Temperatures// maintain decreasing temperature stack // when a warmer day arrives, resolve previous daysLargest Rectangle in Histogram// when a bar is popped, // it becomes the limiting height of the maximal rectangle // width comes from current index and new stack top
Pattern 5: Binary Trees / BST
Recognition Signals
// tree path, depth, diameter, balance
// BST ordering
// layer-by-layer view
// subtree information
Traversal Selection
// preorder: build / serialize / path construction
// inorder: BST sorted order
// postorder: combine left and right subtree info
// level order: BFS by layers
Core Template
def dfs(node):
if not node:
return base_value
left = dfs(node.left)
right = dfs(node.right)
// combine subtree answers here
return something_for_parent
Learning Order
- Maximum Depth of Binary Tree
- Invert Binary Tree
- Binary Tree Inorder Traversal
- Symmetric Tree
- Binary Tree Level Order Traversal
- Diameter of Binary Tree
- Validate Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Kth Smallest Element in a BST
- Lowest Common Ancestor of a Binary Tree
- Binary Tree Right Side View
- Path Sum III
- Flatten Binary Tree to Linked List
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Maximum Path Sum
Problem Notes
Symmetric Tree// compare left subtree of one side with right subtree of the other sideDiameter of Binary Tree// for each node: // longest path through node = left_height + right_height // return height to parentValidate Binary Search Tree// BST is not just local left < root < right // every node must satisfy global lower and upper boundsKth Smallest Element in a BST// inorder traversal of BST is sorted // count visited nodesLowest Common Ancestor of a Binary Tree// if left and right both return non-null, // current node is the LCAPath Sum III// same pattern as subarray sum equals k // prefix sum on a root-to-current pathFlatten Binary Tree to Linked List// reconnect left flattened subtree between root and right subtree // reverse preorder thinking is also commonBinary Tree Maximum Path Sum// return only one-side gain to parent // but update global answer using left + node + right
Pattern 6: Binary Search
Recognition Signals
// sorted input
// first / last occurrence
// minimum valid answer
// rotated sorted array
// monotonic condition
Core Templates
// exact match
left = 0
right = n - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
// left boundary search
while left <= right:
mid = (left + right) // 2
if nums[mid] >= target:
right = mid - 1
else:
left = mid + 1
Learning Order
- Search Insert Position
- Find First and Last Position of Element in Sorted Array
- Search a 2D Matrix
- Find Minimum in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search a 2D Matrix II
- Median of Two Sorted Arrays
Problem Notes
Find First and Last Position of Element// run binary search twice: // once for left boundary // once for right boundaryFind Minimum in Rotated Sorted Array// compare nums[mid] with nums[right] // decide which half must contain the minimumSearch in Rotated Sorted Array// one half is always sorted // determine whether target lies inside that sorted halfMedian of Two Sorted Arrays// binary search partition, not actual merge // make left partition size fixed // ensure maxLeft <= minRight on both arrays
Pattern 7: Sliding Window
Recognition Signals
// substring / subarray
// longest or shortest valid contiguous segment
// no repeated chars
// cover all required chars
// fixed-size window
Core Templates
// variable-size window
left = 0
for right in range(n):
// expand window by including nums[right]
while window is invalid:
// shrink from left
left += 1
// update answer
// fixed-size window
// initialize first k elements
// then slide:
// add right, remove left, update answer
Learning Order
- Longest Substring Without Repeating Characters
- Find All Anagrams in a String
- Minimum Window Substring
- Sliding Window Maximum
Problem Notes
Longest Substring Without Repeating Characters// maintain a window with all unique chars // if duplicate appears, move left until valid againFind All Anagrams in a String// fixed-size frequency window // compare counts against target patternMinimum Window Substring// expand until all required chars are covered // then shrink as much as possible while still validSliding Window Maximum// use deque, not heap, for O(n) // maintain decreasing values in deque
Pattern 8: Backtracking
Recognition Signals
// all combinations
// all permutations
// all partitions
// search every valid choice
// place / remove / undo
Core Template
path = []
def backtrack(state):
if reach_goal:
ans.append(path copy)
return
for choice in available choices:
if choice is invalid:
continue
// choose
path.append(choice)
// explore
backtrack(next_state)
// unchoose
path.pop()
Learning Order
- Letter Combinations of a Phone Number
- Subsets
- Permutations
- Combination Sum
- Generate Parentheses
- Palindrome Partitioning
- Word Search
- N-Queens
Problem Notes
Subsets// classic choose / skip pattern // usually use start index to avoid revisiting previous positionsPermutations// order matters // use used[] to mark chosen elementsCombination Sum// order does not matter // reuse of same element allowed // recursive call often keeps same indexGenerate Parentheses// left_count <= n // right_count <= left_countPalindrome Partitioning// choose a substring cut // continue only if chosen substring is a palindromeWord Search// DFS on matrix // mark visited during current path // restore after backtrackingN-Queens// track used columns, diag1, diag2 // prune invalid queen placements early
Pattern 9: Graph BFS / DFS
Recognition Signals
// islands / connected components
// dependencies / prerequisites
// spread over time
// shortest number of steps in unweighted graph
Core Templates
// DFS flood fill
def dfs(r, c):
if out of bounds or invalid:
return
mark visited
dfs in four directions
// BFS by levels
queue = all starting states
steps = 0
while queue:
for _ in range(len(queue)):
process one node
push next nodes
steps += 1
Learning Order
- Number of Islands
- Rotting Oranges
- Course Schedule
Problem Notes
Number of Islands// count components // once land is found, flood-fill the whole islandRotting Oranges// all rotten oranges are simultaneous BFS sources // each BFS layer represents one minuteCourse Schedule// detect cycle in a directed graph // topological sort using indegree
Pattern 10: Heap / Priority Queue
Recognition Signals
// top k
// streaming median
// repeatedly take smallest / largest
// merge many sorted structures
Core Templates
// keep size-k min heap for k largest elements
for x in nums:
push x
if heap size > k:
pop smallest
// two heaps for median
// left heap: max heap
// right heap: min heap
// rebalance sizes after each insert
Learning Order
- Kth Largest Element in an Array
- Top K Frequent Elements
- Merge k Sorted Lists
- Find Median from Data Stream
Problem Notes
Top K Frequent Elements// count frequencies first // then use heap or bucket sortMerge k Sorted Lists// heap stores current node from each list // repeatedly pop smallest node and push its nextFind Median from Data Stream// maintain lower half and upper half // balance sizes so median is always available
Pattern 11: Dynamic Programming
DP Checklist
// 1. What does dp state mean?
// 2. What is the transition?
// 3. What is the base case?
// 4. What traversal order is valid?
Recognition Signals
// optimal value
// counting ways
// choose or skip
// overlapping subproblems
// "minimum steps", "maximum length", "can we form"
Learning Order
- Climbing Stairs
- Pascal’s Triangle
- House Robber
- Unique Paths
- Minimum Path Sum
- Coin Change
- Perfect Squares
- Word Break
- Partition Equal Subset Sum
- Longest Common Subsequence
- Longest Increasing Subsequence
- Longest Palindromic Substring
- Maximum Product Subarray
- Edit Distance
- Longest Valid Parentheses
Core Templates
// 1D DP
dp[i] = answer for prefix / first i positions
// 2D grid DP
dp[r][c] = answer up to cell (r, c)
// usually from top / left
// string pair DP
dp[i][j] = answer for s1[:i], s2[:j]
Problem Notes
Climbing Stairs// Fibonacci-style DP // dp[i] = dp[i-1] + dp[i-2]House Robber// rob current => cannot rob previous // skip current => inherit previous answerUnique Paths// paths to current cell = from top + from leftMinimum Path Sum// min cost to current cell = cell value + min(top, left)Coin Change// minimum number of coins to make amount // dp[a] = min(dp[a], dp[a - coin] + 1)Perfect Squares// same shape as coin change // available "coins" are square numbersWord Break// dp[i] means s[:i] can be segmented // try all split points j < iPartition Equal Subset Sum// subset-sum / 0-1 knapsack // target is total_sum / 2Longest Common Subsequence// if chars match: // dp[i][j] = dp[i-1][j-1] + 1 // else take max of top / leftLongest Increasing Subsequence// classic O(n^2) DP first // then learn patience sorting + binary searchLongest Palindromic Substring// interval DP or expand-around-center // center expansion is often simplerMaximum Product Subarray// track both max_here and min_here // negative number can swap their rolesEdit Distance// operations: insert / delete / replace // pick min among those transitionsLongest Valid Parentheses// either stack solution or DP // good problem for understanding "ends-at-i" state
Common Mistakes
- Writing a recurrence before defining state clearly
- Wrong base cases
- Wrong iteration order
- Mixing “exactly i” with “up to i”
Pattern 12: Matrix Problems
Recognition Signals
// 2D traversal
// in-place transform
// search in rows/cols
// DFS/BFS on grid
Learning Order
- Rotate Image
- Spiral Matrix
- Set Matrix Zeroes
- Search a 2D Matrix
- Search a 2D Matrix II
- Number of Islands
- Rotting Oranges
- Word Search
Matrix Checklist
// 1. what are the valid neighbors?
// 2. do I need visited?
// 3. can I modify the matrix in place?
// 4. will a cell be processed multiple times?
// 5. where are the boundary checks?
Pattern 13: Trie
Problem
- Implement Trie (Prefix Tree)
Core Idea
// Trie stores characters level by level
// node.children[ch]
// node.is_end marks complete words
Use Cases
- Prefix search
- Dictionary lookups
- Word search extensions
Pattern 14: Greedy
Recognition Signals
// local best choice seems to preserve global optimality
// jump coverage
// interval-like cutting
// maximize reach / minimize steps with current best boundary
Learning Order
- Best Time to Buy and Sell Stock
- Jump Game
- Jump Game II
- Partition Labels
Problem Notes
Jump Game// maintain farthest reachable index // if current index exceeds it, failJump Game II// current_end = boundary of current jump // farthest = best next boundary // when reaching current_end, commit one jumpPartition Labels// a segment must extend to the last occurrence of every char inside it
Hard Problems To Leave For The End
- Median of Two Sorted Arrays
- Binary Tree Maximum Path Sum
- Longest Valid Parentheses
- Find Median from Data Stream
- Merge k Sorted Lists
- Reverse Nodes in k-Group
- Sliding Window Maximum
- Largest Rectangle in Histogram
- Trapping Rain Water
- First Missing Positive
- N-Queens
- Edit Distance
- Minimum Window Substring
Reason:
// these are not random hard problems
// they are combinations of earlier core patterns
6-Phase Completion Plan
Phase 1: Build Core Reflexes
- Two Sum
- Best Time to Buy and Sell Stock
- Maximum Subarray
- Move Zeroes
- Reverse Linked List
- Merge Two Sorted Lists
- Valid Parentheses
- Maximum Depth of Binary Tree
- Invert Binary Tree
- Binary Tree Inorder Traversal
- Search Insert Position
- Climbing Stairs
- House Robber
- Longest Substring Without Repeating Characters
- Number of Islands
Phase 2: Consolidate Mid-Level Templates
- 3Sum
- Product of Array Except Self
- Merge Intervals
- Linked List Cycle
- Remove Nth Node From End of List
- Add Two Numbers
- Diameter of Binary Tree
- Validate Binary Search Tree
- Binary Tree Level Order Traversal
- Kth Smallest Element in a BST
- Search in Rotated Sorted Array
- Find First and Last Position of Element
- Subsets
- Permutations
- Combination Sum
- Course Schedule
- Rotting Oranges
- Daily Temperatures
- Top K Frequent Elements
- Coin Change
- Word Break
- Unique Paths
- Minimum Path Sum
Phase 3: Trees / Window / Backtracking Strength
- Lowest Common Ancestor of a Binary Tree
- Path Sum III
- Binary Tree Right Side View
- Flatten Binary Tree to Linked List
- Letter Combinations of a Phone Number
- Generate Parentheses
- Palindrome Partitioning
- Word Search
- Find All Anagrams in a String
- Partition Equal Subset Sum
- Longest Common Subsequence
- Implement Trie
Phase 4: Data Structures and Advanced Array Work
- Group Anagrams
- Longest Consecutive Sequence
- Subarray Sum Equals K
- Sort Colors
- Rotate Array
- Next Permutation
- Find the Duplicate Number
- Copy List with Random Pointer
- Sort List
- LRU Cache
- Kth Largest Element in an Array
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Minimum in Rotated Sorted Array
Phase 5: Controlled Hard Problems
- Trapping Rain Water
- Largest Rectangle in Histogram
- Sliding Window Maximum
- Minimum Window Substring
- Edit Distance
- Binary Tree Maximum Path Sum
- Merge k Sorted Lists
- Reverse Nodes in k-Group
- Find Median from Data Stream
- First Missing Positive
- N-Queens
Phase 6: Final Bosses
- Median of Two Sorted Arrays
- Longest Valid Parentheses
Daily Practice Format
Use this every day:
- One new template problem
- One same-pattern medium problem
- One review problem from the last 3 days
Example
// Day structure
// Problem A: learn template
// Problem B: apply template
// Problem C: re-solve from memory
Why this works:
// random solving builds familiarity
// grouped repetition builds pattern memory
Review Rules
If you cannot solve a problem:
// do not just read and move on
// instead write:
// 1. pattern
// 2. key invariant
// 3. why your attempt failed
// 4. the reusable template
If you solved it but slowly:
// mark it as "redo in 2 days"
If you solved it cleanly:
// mark it as "review in 1 week"
One-Line Pattern Summary
Hashing: use memory to remove repeated searchingTwo pointers: use relative position to shrink workSliding window: maintain a valid contiguous rangeLinked list: dummy node + pointer rewiringStack: process nested or nearest relationshipsMonotonic stack: solve next greater/smaller efficientlyTree DFS: ask each subtree to return useful informationBFS: expand level by levelBinary search: cut by monotonicityBacktracking: try, recurse, undoHeap: keep top-k or next-best candidatesDP: define state and build from smaller subproblems
Recommended Next Step
Start with this exact block:
- Two Sum
- Best Time to Buy and Sell Stock
- Maximum Subarray
- Move Zeroes
- Reverse Linked List
- Merge Two Sorted Lists
- Valid Parentheses
- Maximum Depth of Binary Tree
- Search Insert Position
- Climbing Stairs
Goal of this block:
// build confidence fast
// cover the most reusable basic templates
// make later medium problems much easier
After This File
Best continuation:
- Make a second document:
pattern_1_arrays_hashing_detailed.md - Teach each problem with:
- recognition signal
- brute force idea
- optimal idea
- commented template
- common mistakes
- mini checklist
That is the right next move if you want a true guided path instead of only a roadmap.