The complete guide to all 30 LeetCode coding interview patterns and LeetCode topics — Sliding Window, Two Pointers, Dynamic Programming, and more.
30 patterns
Find optimal subarrays or substrings (max sum, longest without repeats) in O(n) instead of O(n²).
When to Use
•
Subarray/substring with a constraint (size K, sum equals X, at most K distinct)
•
Contiguous sequence optimization (max, min, longest, shortest)
•
Problem mentions 'window', 'consecutive', or 'contiguous'
Approach
Avoid recomputing overlapping elements: add the entering element, remove the leaving one. Two pointers (left, right) track window boundaries—expand right to grow, shrink left when constraint breaks.
Time:
O(n)Space:
O(k) where k is the window size or distinct elementsSolve sorted array problems (pair sums, 3Sum, duplicates) in O(n) by moving pointers from both ends or together.
When to Use
•
Sorted array + find pair/triplet with target sum
•
Remove duplicates or partition array in-place
•
Compare elements from opposite ends (palindrome, container with most water)
Approach
Place pointers at start/end (or both at start). Move based on comparison: sum too small → move left pointer right; sum too large → move right pointer left. Eliminates nested loops.
Time:
O(n)Space:
O(1)Detect cycles in linked lists or sequences without extra space—if fast catches slow, there's a loop.
When to Use
•
Linked list has a cycle? Find where it starts?
•
Find middle node in one pass (fast hits end → slow is at middle)
•
Repeating sequence detection (happy number, duplicate finder)
Approach
Slow moves 1 step, fast moves 2 steps. If they meet, there's a cycle. To find cycle start: reset one pointer to head, move both at speed 1—they meet at the cycle entrance.
Time:
O(n)Space:
O(1)Handle overlapping ranges (time slots, meetings, intervals)—merge them, find gaps, or count conflicts.
When to Use
•
Input is a list of [start, end] intervals
•
Merge overlapping ranges or insert a new interval
•
Count conflicts / minimum resources needed (meeting rooms)
Approach
Sort by start time, then scan: if current overlaps previous, merge by extending end time. Key insight: after sorting, you only need to compare adjacent intervals.
Time:
O(n log n) due to sortingSpace:
O(n) for the outputExample Problems
Find missing or duplicate numbers in O(n) time and O(1) space when array contains values 1 to N.
When to Use
•
Array contains numbers in range [1, N] or [0, N]
•
Find missing number, duplicate number, or first missing positive
•
Must solve in O(1) extra space
Approach
Each number has a 'home' index (value - 1). Swap each number to its home until the current position is correct. After one pass, misplaced positions reveal missing/duplicate values.
Time:
O(n)Space:
O(1)Reverse all or part of a linked list without extra memory—essential for many list manipulation problems.
When to Use
•
Reverse entire list, a sublist (m to n), or every K nodes
•
Check if linked list is palindrome
•
Reorder list (interleave first and last halves)
Approach
Three pointers: prev, curr, next. Save next, point curr.next to prev, then advance all three. The trick for sublists: save the node before reversal starts to reconnect after.
Time:
O(n)Space:
O(1)Process a tree level-by-level—minimum depth, level averages, zigzag, or connect siblings at same depth.
When to Use
•
Need nodes grouped by level (level order, level sums/averages)
•
Find minimum depth or shortest path in tree
•
Connect nodes at the same level (next pointers)
Approach
Use a queue. Process all nodes at current level (queue size tells you how many), then add their children for the next level. Each iteration = one level of the tree.
Time:
O(n)Space:
O(w) where w is the maximum width of the treeSolve path problems (sum to target, all root-to-leaf paths) and validate tree properties (BST, balanced).
When to Use
•
Find path with target sum or collect all paths
•
Validate structure (is BST? is balanced? is symmetric?)
•
Calculate tree properties (diameter, max depth, LCA)
Approach
Recursively solve for left and right subtrees, combine results at current node. The key is defining what info to return: boolean, count, height, or path list—depends on the problem.
Time:
O(n)Space:
O(h) where h is the height of the treeExample Problems
Find running median in O(log n) per insert—split data into 'small half' and 'large half' using two heaps.
When to Use
•
Median from data stream or sliding window median
•
Need quick access to both the largest of small elements and smallest of large elements
•
Scheduling with constraints on both ends
Approach
Max-heap holds the smaller half, min-heap holds the larger half. After each insert, rebalance so sizes differ by at most 1. Median is top of the larger heap (or average of both tops).
Time:
O(log n) per insertionSpace:
O(n)Example Problems
Generate all subsets, permutations, or combinations—the go-to approach when you need 'all possible' answers.
When to Use
•
Generate all subsets, permutations, or combinations
•
Combination sum: find subsets that sum to target
•
Problem asks for 'all possible' results or 'number of ways'
Approach
Recursively explore two choices at each element: include it or skip it. For permutations, swap elements into position. For duplicates, sort first and skip consecutive same values to avoid duplicate results.
Time:
O(2^n) for subsets, O(n!) for permutationsSpace:
O(n) for recursion depthExample Problems
Search rotated arrays, find first/last occurrence, or locate boundaries in O(log n) with tweaked binary search.
When to Use
•
Sorted or rotated sorted array—search for value or find rotation point
•
Find first or last occurrence of target (upper/lower bound)
•
Search space can be halved based on a condition (not just equality)
Approach
Standard binary search but change the condition for choosing halves. For rotated arrays: identify which half is sorted, then check if target lies in that range. For boundaries: don't stop at first match, keep going.
Time:
O(log n)Space:
O(1)Find K largest, smallest, or most frequent elements in O(n log k) using a heap of size K.
When to Use
•
K largest / smallest / closest / most frequent
•
Kth largest element (Quickselect alternative)
•
Sort by frequency or custom ranking
Approach
For K largest: use a min-heap of size K—if new element > heap top, pop and push. Heap always holds the K largest seen so far. For frequency: first count with hash map, then heap by count.
Time:
O(n log k) with heap, O(n) average with quickselectSpace:
O(k)Merge K sorted lists into one sorted output in O(n log k)—essential for 'merge k' and 'kth smallest in matrix' problems.
When to Use
•
Merge K sorted lists or arrays
•
Kth smallest element in a sorted matrix
•
Smallest range covering elements from K lists
Approach
Min-heap holds one element from each list (with list index). Pop smallest, add to result, push next element from that same list. Heap size stays at K, giving O(log k) per element.
Time:
O(n log k) where n is total elements and k is number of listsSpace:
O(k) for the heapOrder tasks so dependencies come first—solves course scheduling, build order, and cycle detection in directed graphs.
When to Use
•
Ordering with prerequisites (courses, tasks, compilation)
•
Detect cycle in a directed graph
•
Find any valid ordering or check if one exists
Approach
Kahn's algorithm: track in-degree of each node, start with zero-degree nodes, process them and decrease neighbors' in-degrees. If you process all nodes, no cycle; otherwise cycle exists.
Time:
O(V + E)Space:
O(V + E)Find the one unique number among duplicates in O(n) time, O(1) space using XOR's self-canceling property.
When to Use
•
Single number among pairs (every element appears twice except one)
•
Find two unique numbers among pairs
•
Missing number without extra space
Approach
XOR all elements: duplicates cancel (a ^ a = 0), unique number remains. For two unique numbers: XOR all gives x ^ y, use any set bit to split array into two groups, XOR each group separately.
Time:
O(n)Space:
O(1)Example Problems
Find next/previous greater or smaller element for every position in O(n)—key for histogram and span problems.
When to Use
•
Next greater / next smaller element
•
Previous greater / previous smaller element
•
Largest rectangle in histogram, maximal rectangle
Approach
Stack holds indices of elements in monotonic order. When new element breaks the order, pop and process (popped element found its next greater/smaller). What remains on stack hasn't found its answer yet.
Time:
O(n)Space:
O(n)Count islands, fill regions, or find shortest path in a grid using BFS/DFS from each unvisited cell.
When to Use
•
Count connected regions (number of islands)
•
Flood fill, surrounded regions, rotting oranges
•
Shortest path in unweighted grid (BFS)
Approach
For counting: loop through grid, when you hit unvisited land, run DFS/BFS to mark the entire island, increment count. For shortest path: BFS guarantees minimum steps. Mark visited in-place or use a set.
Time:
O(m * n)Space:
O(m * n) in worst case for visited trackingExample Problems
Solve optimization by always picking the locally best option—works for interval scheduling, jump games, and more.
When to Use
•
Interval scheduling (max non-overlapping, min meeting rooms)
•
Can reach end? Min jumps to reach end?
•
Assign/distribute to minimize cost or maximize coverage
Approach
At each step, pick the locally optimal choice. Greedy works when this doesn't hurt future choices—often true for intervals (pick earliest end) and reachability (extend farthest reach).
Time:
Varies, often O(n log n) due to sortingSpace:
O(1) to O(n)Example Problems
Answer range sum queries in O(1) after O(n) preprocessing—unlocks 'subarray sum equals K' problems.
When to Use
•
Multiple range sum queries on static array
•
Subarray sum equals K (combine with hash map)
•
Count subarrays with sum divisible by K, equal 0/1 balance
Approach
prefix[i] = sum of elements 0..i-1. Range sum [i,j] = prefix[j+1] - prefix[i]. For 'subarray = K': if prefix[j] - prefix[i] = K, then prefix[i] = prefix[j] - K—use hash map to find matching prefix in O(1).
Time:
O(n) preprocessing, O(1) per querySpace:
O(n)Choose items with weight constraints to maximize value—solves partition, subset sum, and bounded selection problems.
When to Use
•
Subset with target sum (partition equal subset sum)
•
Choose/not choose with capacity constraint
•
Bounded item selection (can only use each item once)
Approach
For each item, decide to include or exclude. dp[i][w] = max value using first i items with capacity w. Recurrence: dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]). Space can be optimized to O(capacity) by iterating backwards.
Time:
O(n * capacity)Space:
O(n * capacity) or O(capacity) optimizedItems can be used unlimited times—solves coin change, rod cutting, and ribbon cutting problems.
When to Use
•
Items can be selected multiple times (unlimited supply)
•
Minimize/maximize with repeatable choices
•
Coin change, rod cutting variations
Approach
Similar to 0/1 knapsack, but when including an item, stay at the same item (don't move to next). dp[i][w] = max(dp[i-1][w], dp[i][w-weight[i]] + value[i]). Notice we use dp[i] not dp[i-1] for the include case.
Time:
O(n * capacity)Space:
O(capacity) with optimizationExample Problems
Current state depends on previous 1-2 states—the simplest DP pattern for sequences and counting paths.
When to Use
•
State depends on previous 1-2 states
•
Counting ways to reach a position
•
Sequence where each term builds on prior terms
Approach
Define dp[i] as the answer for position i. Recurrence: dp[i] = dp[i-1] + dp[i-2] (or similar). Only need to track last 2 values, so space reduces to O(1). Base cases: dp[0] and dp[1].
Time:
O(n)Space:
O(1) with space optimizationExample Problems
Find or count palindromes in strings using DP—expand from center or use 2D table comparing string with its reverse.
When to Use
•
Longest palindromic substring/subsequence
•
Count palindromic substrings
•
Minimum deletions to make palindrome
Approach
For substrings: expand around each center (O(n²)) or dp[i][j] = true if s[i..j] is palindrome. For subsequences: dp[i][j] = length of longest palindromic subsequence in s[i..j]. If s[i]==s[j], dp[i][j] = dp[i+1][j-1] + 2.
Time:
O(n²)Space:
O(n²) or O(n) with optimizationCompare two sequences to find common parts—covers LCS, edit distance, and sequence alignment problems.
When to Use
•
Find longest common subsequence/substring
•
Calculate edit distance between strings
•
Sequence alignment or interleaving
Approach
2D DP where dp[i][j] represents answer for first i chars of string1 and first j chars of string2. If chars match, extend from dp[i-1][j-1]. Otherwise, take best of dp[i-1][j] or dp[i][j-1] depending on problem.
Time:
O(m * n)Space:
O(m * n) or O(min(m, n)) with optimizationBFS/DFS on general graphs with cycle handling—covers shortest paths, connectivity, and traversal beyond trees.
When to Use
•
Shortest path in unweighted graph (BFS)
•
Detect cycles in directed/undirected graphs
•
Find connected components or reachability
Approach
Build adjacency list from edges. BFS for shortest path (unweighted): use queue, track visited, level = distance. DFS for connectivity/cycles: use visited set, for directed graphs track 'in current path' to detect back edges.
Time:
O(V + E)Space:
O(V + E) for adjacency listLIFO structure for matching pairs, tracking state, and evaluating expressions—essential for parentheses and calculator problems.
When to Use
•
Matching parentheses/brackets
•
Evaluate expressions (postfix, calculator)
•
Track nested state or undo operations
Approach
Push opening brackets/operators, pop when closing/lower precedence found. For expressions: use two stacks (operands + operators) or convert to postfix first. Stack naturally handles nesting and LIFO order.
Time:
O(n)Space:
O(n)O(1) lookup for frequency counting, pair finding, and caching—turns O(n²) brute force into O(n).
When to Use
•
Count frequencies (anagrams, duplicates)
•
Find pairs with target sum
•
Cache previously seen values
Approach
Store key-value pairs for O(1) access. For Two Sum: map value → index, check if complement exists. For frequency: map element → count. For caching: map input → computed result (memoization).
Time:
O(1) average per operationSpace:
O(n)Example Problems
Maintain sorted elements with O(log n) insert/delete/search—useful for sliding window with rank queries.
When to Use
•
Need sorted order with dynamic insertions/deletions
•
Find k-th smallest in sliding window
•
Range queries on dynamic data
Approach
Use TreeSet (Java), SortedList (Python), or balanced BST. Supports O(log n) insert, delete, and finding floor/ceiling values. Combine with sliding window for problems requiring sorted access in a window.
Time:
O(log n) per insert/delete/searchSpace:
O(n)Store and search strings by prefix in O(word length)—powers autocomplete, word search, and prefix matching.
When to Use
•
Search words by prefix (autocomplete, startsWith)
•
Word search in 2D board (backtrack + trie)
•
Count/find words with common prefix
Approach
Each node has children map (char → node) and isEnd flag. Insert: walk down creating nodes. Search/startsWith: walk down, check if path exists. Trie turns repeated prefix matching from O(n*m) to O(m).
Time:
O(m) per operation where m is word lengthSpace:
O(alphabet_size * m * n) for n wordsGroup elements into connected components with near O(1) union and find—ideal for dynamic connectivity.
When to Use
•
Count or check connected components as edges are added
•
Detect cycle in undirected graph (if union finds same root)
•
Merge accounts, friend circles, or equivalence classes
Approach
parent[i] points to i's parent (or self if root). find(x): follow parents to root with path compression. union(x,y): link roots, use rank to keep tree flat. Same root = same component.
Time:
O(α(n)) per operation (nearly constant with optimizations)Space:
O(n)Companies:
Fewer
More
Category:
18 topicsArray
String
Hash
Matrix
Tree
Heap
BinTree
Stack
List
OrdSet
SegTree
Trie
Queue
BIT
BST
HashFn
DblList
SufArr
1280
530
495
201
167
142
129
128
68
50
41
41
42
23
33
22
10
2
Amazon
1086
434
424
150
159
129
133
120
67
38
25
32
36
16
33
18
11
5
Microsoft
731
313
286
115
114
78
95
89
60
21
10
22
27
7
27
11
10
Meta
724
301
287
107
123
81
111
91
59
20
13
24
25
10
29
12
8
2
Bloomberg
638
260
260
93
89
74
83
81
53
16
13
19
22
8
22
12
6
2
Uber
237
85
90
50
24
34
15
21
14
15
6
17
9
2
3
8
5
1
TikTok
205
98
79
37
34
28
31
35
21
6
4
15
3
2
6
3
4
1
Oracle
170
86
75
26
26
23
24
28
32
4
2
10
5
1
4
2
4
Apple
167
80
73
31
24
22
22
25
24
7
3
8
10
2
5
2
4
Goldman Sachs
154
68
60
25
15
21
13
23
16
3
2
5
8
3
3
2
3
1
TCS
117
43
43
12
6
9
6
12
16
1
3
1
1
Salesforce
111
52
47
13
19
24
15
22
7
3
1
3
4
3
2
3
IBM
105
55
36
8
1
13
1
16
6
3
1
2
4
1
1
82
38
39
9
26
11
25
17
13
2
2
1
2
7
2
5
Zoho
102
67
41
20
7
16
4
3
3
1
Infosys
106
35
29
6
6
9
3
14
9
3
3
1
1
2
1
Adobe
91
36
31
15
14
10
12
12
7
1
4
3
1
3
1
Walmart Labs
85
38
35
14
6
13
5
13
11
2
1
3
5
1
1
3
1
Accenture
72
37
28
6
5
4
5
8
6
1
2
1
1
Visa
96
38
36
18
5
16
5
10
5
3
2
5
4
1
2
2
NVIDIA
73
26
28
10
4
13
4
12
18
2
1
2
3
1
1
1
Yandex
70
30
37
6
11
8
11
9
9
1
7
3
1
De Shaw
77
26
19
10
4
13
2
12
1
1
2
2
1
1
1
Flipkart
73
16
20
15
11
15
11
16
3
3
1
2
1
PayPal
74
26
26
10
3
8
2
6
5
2
1
2
PhonePe
72
20
23
11
5
10
3
10
1
2
1
1
3
1
1
1
Snowflake
52
30
27
8
11
10
9
7
11
3
1
7
3
1
2
Citadel
55
22
24
10
4
11
4
2
5
1
4
4
1
1
3
Snapchat
47
33
23
16
4
6
4
10
5
1
5
1
2
1
3
DoorDash
47
24
21
15
6
9
6
9
5
1
6
1
3
Cisco
42
24
18
8
5
6
3
4
7
3
2
2
2
1
Servicenow
42
22
18
5
3
4
2
11
6
1
1
2
2
JPMorgan
44
24
22
3
1
12
1
3
1
1
2
1
Intuit
43
18
14
9
2
6
1
8
3
2
4
2
1
2
1
1
1
Bytedance
36
18
16
7
4
4
4
8
8
1
1
1
Samsung
44
12
12
9
3
10
2
3
4
3
2
1
1
1
Nutanix
38
13
14
11
6
7
6
6
7
2
2
1
3
1
3
Qualcomm
25
13
8
3
2
4
2
4
10
1
4
1
Airbnb
36
22
19
9
2
3
1
4
4
1
4
1
1
1
Atlassian
43
17
24
4
5
7
5
3
2
3
2
3
Capital One
44
18
18
7
1
3
1
3
2
4
2
4
1
2
3
1
Expedia
29
23
16
3
3
5
3
8
2
1
1
3
1
2
Ebay
34
18
14
9
2
8
2
5
4
2
1
2
1
1
1
1
Roblox
40
13
22
8
5
5
2
3
1
4
3
1
1
Wix
31
22
17
7
8
3
8
3
4
3
2
1
Morgan Stanley
39
12
16
2
2
8
5
3
1
1
Anduril
34
13
11
12
4
4
4
6
4
2
1
1
1
20
15
14
4
2
7
1
4
6
2
1
2
2
1
1
2
Epam Systems
24
16
11
2
1
3
1
3
4
1
1
1
Coupang
28
18
15
3
1
7
1
6
4
1
1
2
2
1
3
2
2
Top companies for Data Structures:
Amazon
Microsoft
Meta
Bloomberg
Uber
Common questions about coding interview patterns and how to master them effectively.
The most common LeetCode patterns that appear frequently in coding interviews are: Two Pointers (used in ~15% of problems), Sliding Window (~12%), Binary Search variations (~10%), Tree DFS/BFS (~15%), and Dynamic Programming (~20%). Hash maps and arrays are fundamental data structures used across most patterns. Mastering these common patterns will prepare you for the majority of common LeetCode interview questions at companies like Google, Meta, Amazon, and Microsoft.
Grokking the Coding Interview popularized the pattern-based approach to coding interviews by organizing LeetCode problems into core patterns — Sliding Window, Two Pointers, Fast & Slow Pointers, Merge Intervals, and others. This guide covers all 30 of those coding interview patterns, including Monotonic Stack, Union Find, Trie, and more. Whether you're working through Grokking the Coding Interview or preparing directly from LeetCode, the underlying patterns are the same.
LeetCode topics (also called categories or tags) are LeetCode's own labels for problems — Arrays, Hash Tables, Trees, Dynamic Programming, Graphs, and so on. LeetCode patterns are the algorithmic techniques you apply to solve problems — Sliding Window, Two Pointers, Fast & Slow Pointers, and so on. A single pattern often applies across multiple topics: the Two Pointers pattern works on Arrays, Strings, and Linked Lists. This page covers both: the Patterns tab teaches the 30 coding interview patterns, and the Topics by Company tab shows which LeetCode topics each company asks most.
Yes — each LeetCode pattern follows a recognizable code template. For example, the Sliding Window template uses two pointers and a running window size variable; the Binary Search template uses lo/hi/mid with a convergence condition. Learning these templates helps you code faster under interview pressure. Each pattern in this guide includes the core approach, time/space complexity, and example problems to practice the template.
To effectively use Grokking patterns for LeetCode, start by learning one pattern at a time and understanding its core concept. Then, practice 3-5 LeetCode problems that use that pattern before moving to the next. Focus on recognizing the pattern indicators in problem statements—keywords like 'contiguous subarray' suggest Sliding Window, while 'sorted array' often indicates Two Pointers or Binary Search. Our guide includes pattern recognition tips and curated problem lists for each pattern.
All 30. The patterns on this page cover everything you'll encounter in coding interviews — from the most common (Sliding Window, Two Pointers, Dynamic Programming) to the more advanced (Monotonic Stack, Union Find, Trie). Use the Topics by Company tab to see which patterns your target companies test most and prioritize accordingly.
Learning all essential LeetCode patterns typically takes 2-4 months with consistent daily practice of 1-2 hours. A structured approach is: spend 1-2 weeks per major pattern category, solving 5-10 problems of increasing difficulty. The key is deliberate practice—understanding why a pattern works, not just memorizing solutions.
© 2026 CodingInterviewAI. All rights reserved