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
1246
527
487
187
165
140
127
127
67
50
39
41
41
23
33
23
10
2
Amazon
1057
433
415
139
161
125
136
127
67
44
25
31
36
16
33
17
11
5
Meta
733
306
299
108
121
83
110
91
62
20
14
25
27
11
29
13
8
2
Microsoft
710
307
284
102
115
79
97
87
61
22
10
23
27
7
27
11
10
Bloomberg
628
259
261
90
88
73
82
81
51
17
13
19
21
8
22
12
6
2
TikTok
216
111
90
39
33
33
31
39
21
6
4
15
3
2
7
4
4
1
Uber
243
88
98
50
27
35
18
23
15
16
7
15
9
2
5
8
5
1
Apple
196
92
85
33
25
24
23
30
26
8
3
11
8
2
6
2
3
Oracle
174
93
80
26
32
23
30
32
34
4
2
10
5
1
8
2
6
Goldman Sachs
161
66
62
27
14
21
12
24
18
2
2
5
8
3
3
2
2
1
Adobe
122
52
48
19
18
15
17
18
14
1
2
4
2
2
5
1
TCS
116
44
41
13
6
11
6
11
15
1
2
1
1
Salesforce
114
49
44
14
19
22
15
23
7
4
1
4
3
3
2
3
83
42
39
9
27
12
25
17
12
3
2
2
1
6
2
6
Zoho
107
67
42
20
7
16
5
3
3
1
IBM
100
53
32
8
1
11
1
15
6
3
1
2
4
1
1
Infosys
98
33
27
6
5
9
3
11
8
3
2
1
3
2
1
Walmart Labs
86
40
36
14
10
14
9
14
11
2
1
3
5
1
1
3
1
Accenture
73
38
31
7
4
5
4
8
7
1
2
1
1
NVIDIA
73
29
28
10
6
13
6
10
18
2
1
3
3
1
3
2
2
Yandex
71
31
42
4
13
7
12
10
9
2
7
3
1
De Shaw
86
27
22
14
5
14
3
14
3
1
1
2
2
2
1
1
Visa
85
33
33
17
5
12
5
8
5
3
1
3
3
1
2
2
Flipkart
79
19
21
16
12
16
12
19
2
3
1
2
PayPal
74
27
26
11
3
8
2
7
5
3
2
Snowflake
54
32
27
10
11
9
9
6
11
2
1
7
2
1
1
PhonePe
70
20
24
11
5
10
3
9
2
2
1
2
1
1
1
Snapchat
54
38
27
17
5
8
5
13
6
1
5
2
1
4
Citadel
58
23
24
9
4
11
4
4
5
1
3
4
1
1
3
DoorDash
53
25
24
16
6
14
5
9
5
1
7
1
3
Cisco
48
25
18
8
5
6
3
5
7
3
2
2
2
1
JPMorgan
48
25
22
4
1
11
1
4
2
1
2
1
Servicenow
47
23
19
7
3
5
2
11
6
1
1
2
2
Intuit
42
20
15
8
2
5
1
10
3
2
3
2
1
2
1
1
1
Samsung
44
12
12
8
4
11
3
3
5
3
2
2
1
1
Nutanix
40
13
16
11
6
7
6
6
8
2
2
1
2
1
3
Airbnb
37
23
20
9
4
3
2
5
5
1
4
2
1
1
1
Bytedance
35
19
17
7
3
4
3
8
8
1
1
1
Yahoo
37
16
19
7
4
3
3
6
5
2
3
1
1
Atlassian
43
18
26
4
5
7
5
3
2
3
2
3
Ebay
37
19
15
9
2
8
2
4
4
1
2
1
1
1
Capital One
42
17
16
7
1
3
1
3
2
4
1
4
1
1
3
1
Qualcomm
21
13
9
3
2
4
2
4
9
4
1
Roblox
40
14
23
8
4
5
2
3
1
4
2
1
1
Wix
31
22
17
7
8
3
8
3
4
3
2
1
Expedia
29
21
16
3
2
4
2
6
1
1
2
1
1
Coupang
28
20
16
3
1
9
1
7
4
1
1
2
2
1
3
2
2
Morgan Stanley
34
15
15
2
2
7
5
3
1
1
22
15
14
5
2
7
1
4
6
2
1
2
2
1
1
2
Epam Systems
25
17
10
1
1
3
1
3
3
1
1
Top companies for Data Structures:
Amazon
Meta
Microsoft
Bloomberg
TikTok
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