🧩 8 LeetCode Patterns — Detailed Lesson Guide
These 8 patterns cover the vast majority of coding interview problems. Master the recognition
signal for each, and unfamiliar problems start feeling like ones you've already solved.
1. Two Pointers
The core idea: Place one pointer at the start and one at the end of a sorted array (or both at the
start moving at different speeds), then move them toward each other based on a condition —
eliminating the need for a nested loop.
When to use it: The problem involves a sorted array or string, and you're searching for a pair
(or triplet) that satisfies some condition — a sum, a difference, a palindrome check. The classic
trigger phrase is "find two numbers that add up to a target."
How it works: Because the array is sorted, you have information: if the sum of the two pointers
is too large, move the right pointer left to decrease it. If too small, move the left pointer right to
increase it. This replaces an O(n²) brute force with an O(n) scan.
Complexity: O(n) time, O(1) space — a major upgrade over brute force.
Landmark problems: Two Sum II (#167), 3Sum (#15), Container With Most Water (#11), Valid
Palindrome (#125).
2. Sliding Window
The core idea: Maintain a "window" — a contiguous subarray or substring — defined by a left
and right pointer, expanding it to the right and shrinking it from the left to find an optimal range
that satisfies some constraint.
When to use it: The problem asks about a contiguous subarray or substring — longest,
shortest, maximum sum, minimum length. Key trigger words: "subarray," "substring,"
"contiguous," "window of size k."
How it works: Expand the right pointer one step at a time. When the window violates the
constraint (e.g., sum exceeds target, or a duplicate character appears), shrink from the left until
the window is valid again. This avoids re-scanning overlapping portions of the array, turning
O(n²) into O(n).
Two flavors: Fixed-size windows (the window never changes size, you just slide it) and
variable-size windows (you expand and contract dynamically).
Complexity: O(n) time, O(1) or O(k) space.
Landmark problems: Longest Substring Without Repeating Characters (#3), Minimum Window
Substring (#76), Maximum Sum Subarray of Size K (#643), Permutation in String (#567).
3. Fast & Slow Pointers (Floyd's Cycle Detection)
The core idea: Use two pointers moving through a linked list (or array) at different speeds —
one moves one step at a time, the other moves two. If there's a cycle, the fast pointer will
eventually lap the slow pointer and they'll meet.
When to use it: Any problem involving a linked list that might have a cycle, or problems that
need to find the middle of a linked list. Trigger phrases: "detect a cycle," "find the middle," "find
the start of the cycle."
How it works: The slow pointer advances by 1, the fast pointer by 2. In a cycle, the distance
between them decreases by 1 each iteration, so they must eventually collide. If the fast pointer
reaches null, there's no cycle. Finding the cycle's entrance requires a second pass from the
head.
Beyond cycle detection: Moving the fast pointer k steps ahead first lets you find the kth node
from the end in a single pass — a common interview trick.
Complexity: O(n) time, O(1) space.
Landmark problems: Linked List Cycle (#141), Find the Duplicate Number (#287), Middle of
the Linked List (#876), Happy Number (#202).
4. Modified Binary Search
The core idea: Binary search isn't just for searching a sorted array for a value — it's a general
technique for halving the search space on any problem where you can determine which half
contains the answer.
When to use it: The input is sorted (or partially sorted, like a rotated sorted array), or the
problem asks for a minimum/maximum value that satisfies some condition (binary search on the
answer). Trigger phrases: "sorted array," "find the target," "minimum possible maximum," "can
you achieve X."
How it works: Maintain left and right bounds. Compute mid = left + (right -
left) // 2. Evaluate a condition at mid — if it tells you the answer is to the right, set left =
mid + 1; if to the left, set right = mid - 1. The tricky part is getting the termination
condition and boundary updates exactly right.
The advanced form — "binary search on answer": For problems like "what's the minimum
speed to eat all bananas?", you binary search over the possible answer values and check
feasibility at each midpoint. This is a powerful generalization.
Complexity: O(log n) time.
Landmark problems: Binary Search (#704), Search in Rotated Sorted Array (#33), Find
Minimum in Rotated Sorted Array (#153), Koko Eating Bananas (#875), Median of Two Sorted
Arrays (#4).
5. Tree BFS (Breadth-First Search / Level Order)
The core idea: Traverse a tree level by level using a queue. Process all nodes at depth 1
before depth 2, all of depth 2 before depth 3, and so on.
When to use it: The problem involves a tree and asks about levels — level order output,
minimum depth, connecting nodes at the same level, right-side view. Trigger phrases: "level
order," "level by level," "minimum depth," "nearest," "shortest path."
How it works: Start by enqueuing the root. At each step, record the current queue size (that's
the width of the current level), process exactly that many nodes, enqueue their children, and
repeat. This cleanly separates levels without needing to track depth explicitly.
Complexity: O(n) time, O(w) space where w is the maximum width of the tree (worst case O(n)
for a complete tree).
Landmark problems: Binary Tree Level Order Traversal (#102), Minimum Depth of Binary Tree
(#111), Binary Tree Right Side View (#199), Populating Next Right Pointers (#116).
6. Tree DFS (Depth-First Search)
The core idea: Traverse a tree by going as deep as possible down one branch before
backtracking, using recursion (or an explicit stack). The three orderings — preorder (root → left
→ right), inorder (left → root → right), postorder (left → right → root) — each have distinct use
cases.
When to use it: Problems about paths, path sums, tree structure validation, or any problem
where you need to carry information downward from parent to children, or upward from children
to parent. Trigger phrases: "path sum," "validate BST," "diameter," "max depth," "all paths."
How it works: Recursively visit left and right subtrees. The choice of preorder vs inorder vs
postorder determines what you do with the current node relative to the recursive calls. Passing
parameters down (like a running sum) handles parent-to-child information; returning values up
(like subtree height) handles child-to-parent aggregation.
Inorder on BSTs is special: Inorder traversal of a BST produces elements in sorted order — a
critical property for BST-specific problems.
Complexity: O(n) time, O(h) space where h is the height of the tree (O(log n) for balanced, O(n)
worst case).
Landmark problems: Maximum Depth of Binary Tree (#104), Path Sum (#112), Validate Binary
Search Tree (#98), Diameter of Binary Tree (#543), Lowest Common Ancestor (#236).
7. Top K Elements (Heap)
The core idea: When you repeatedly need the largest or smallest element from a changing
collection, use a heap (priority queue). It gives O(1) access to the extreme element and O(log n)
insertion and deletion.
When to use it: The problem asks for the k largest, k smallest, k most frequent, or k closest
elements. Or it involves a stream of data where you need a running min/max. Trigger phrases:
"top k," "k largest," "k most frequent," "kth largest."
How it works: For "k largest elements," use a min-heap of size k. Iterate through all elements
— push each onto the heap, and if the heap exceeds size k, pop the minimum. At the end, the
heap contains exactly the k largest. This avoids sorting the entire array (O(n log n)) and costs
only O(n log k).
The Two Heaps variant: For problems involving medians of a data stream, maintain a
max-heap for the lower half and a min-heap for the upper half, balanced in size. The median is
always at the top of one or both heaps.
Complexity: O(n log k) time, O(k) space — better than full sort when k ≪ n.
Landmark problems: Kth Largest Element in an Array (#215), Top K Frequent Elements
(#347), K Closest Points to Origin (#973), Find Median from Data Stream (#295).
8. Dynamic Programming (DP)
The core idea: Break a problem into overlapping subproblems, solve each subproblem once,
and cache the result so it's never recomputed. DP applies when the optimal solution to the
whole problem can be built from optimal solutions to smaller sub-problems (optimal
substructure).
When to use it: Problems asking for number of ways, minimum cost, maximum profit, can you
achieve X, or longest/shortest something where choices at each step affect future choices.
Trigger phrases: "how many ways," "minimum steps," "maximum sum," "can you reach,"
"longest increasing subsequence."
How it works: There are two equivalent formulations. Top-down (memoization): write the
natural recursive solution and add a cache (dictionary or array) to store computed results.
Bottom-up (tabulation): identify the base cases and iteratively fill a table from smallest
subproblem to largest. Both yield the same answer; top-down is often easier to reason about,
bottom-up often uses less stack space.
DP has sub-patterns worth learning individually: 1D DP (Climbing Stairs, House Robber), 2D
DP (grid paths, edit distance), 0/1 Knapsack, Unbounded Knapsack, Interval DP, and
subsequence DP (Longest Common Subsequence).
The key recognition test: Can you define a state (what information captures where you are in
the problem) and a recurrence (how the answer for this state depends on smaller states)? If
yes, it's DP.
Complexity: Varies — typically O(n), O(n²), or O(n·m) time with matching space (often
reducible with space optimization).
Landmark problems: Climbing Stairs (#70), House Robber (#198), Coin Change (#322),
Longest Common Subsequence (#1143), 0/1 Knapsack, Word Break (#139).
Quick Recognition Cheat Sheet
Signal in the problem Pattern to reach for
Sorted array, find pair/triplet Two Pointers
Contiguous subarray/substring, longest/shortest Sliding Window
Linked list, cycle, or find middle Fast & Slow Pointers
Sorted input, find target, minimize/maximize a value Modified Binary Search
Tree, level-by-level, shortest path, nearest node Tree BFS
Tree, paths, validate structure, carry info up/down Tree DFS
Top k, k most frequent, k closest, streaming min/max Heap / Top K
Count ways, min/max cost, overlapping Dynamic Programming
subproblems
The meta-skill is pattern recognition before coding — spend 2–3 minutes identifying which
pattern applies before writing a single line. That shift alone is what makes LeetCode go from
overwhelming to manageable.