Leetcode - Common Patterns
Leetcode - Common Patterns
557 20 Share
I have solved more than 1500 LeetCode problems, and if there is one thing I have
learned, it’s this:
LeetCode is less about the number of problems you have solved and more about
how many patterns you know.
Learning patterns enables you to solve a wide variety of problems in lesser time and
helps you quickly identify the right approach to a problem you have never seen
before.
In this article, I’ll walk you through the 15 most important patterns I learned that
made my LeetCode journey lot less painful.
https://blog.algomaster.io/p/15-leetcode-patterns 1/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
I’ll share when to use each pattern along with a sample problem and provide links to
LeetCode problems you can practice to learn these patterns better.
1. Prefix Sum
Prefix Sum involves preprocessing an array to create a new array where each element
at index i represents the sum of the array from the start up to i. This allows for
efficient sum queries on subarrays.
Use this pattern when you need to perform multiple sum queries on a subarray or
need to calculate cumulative sums.
Sample Problem:
Given an array nums, answer multiple queries about the sum of elements within a
specific range [i, j].
Example:
Output: 9
Explanation:
1. Preprocess the array A to create a prefix sum array: P = [1, 3, 6, 10, 15,
21].
https://blog.algomaster.io/p/15-leetcode-patterns 2/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
2. To find the sum between indices i and j, use the formula: P[j] - P[i-1].
LeetCode Problems:
1. Range Sum Query - Immutable (LeetCode #303)
2. Two Pointers
The Two Pointers pattern involves using two pointers to iterate through an array or
list, often used to find pairs or elements that meet specific criteria.
Use this pattern when dealing with sorted arrays or lists where you need to find pairs
that satisfy a specific condition.
Sample Problem:
Find two numbers in a sorted array that add up to a target value.
Example:
Output: [1, 3]
https://blog.algomaster.io/p/15-leetcode-patterns 3/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Explanation:
1. Initialize two pointers, one at the start (left) and one at the end (right) of the
array.
4. If the sum is less than the target, move the left pointer to the right.
5. If the sum is greater than the target, move the right pointer to the left.
LeetCode Problems:
1. Two Sum II - Input Array is Sorted (LeetCode #167)
3. Sliding Window
The Sliding Window pattern is used to find a subarray or substring that satisfies a
specific condition, optimizing the time complexity by maintaining a window of
elements.
https://blog.algomaster.io/p/15-leetcode-patterns 4/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Use this pattern when dealing with problems involving contiguous subarrays or
substrings.
Sample Problem:
Find the maximum sum of a subarray of size k.
Example:
Output: 9
Explanation:
1. Start with the sum of the first k elements.
2. Slide the window one element at a time, subtracting the element that goes out of
the window and adding the new element.
LeetCode Problems:
1. Maximum Average Subarray I (LeetCode #643)
https://blog.algomaster.io/p/15-leetcode-patterns 5/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
The Fast & Slow Pointers (Tortoise and Hare) pattern is used to detect cycles in
linked lists and other similar structures.
Sample Problem:
Detect if a linked list has a cycle.
Explanation:
1. Initialize two pointers, one moving one step at a time (slow) and the other
moving two steps at a time (fast).
2. If there is a cycle, the fast pointer will eventually meet the slow pointer.
3. If the fast pointer reaches the end of the list, there is no cycle.
LeetCode Problems:
1. Linked List Cycle (LeetCode #141)
https://blog.algomaster.io/p/15-leetcode-patterns 6/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
The In-place Reversal of a LinkedList pattern reverses parts of a linked list without
using extra space.
Use this pattern when you need to reverse sections of a linked list.
Sample Problem:
Reverse a sublist of a linked list from position m to n.
Example:
Output: [1, 4, 3, 2, 5]
Explanation:
1. Identify the start and end of the sublist.
LeetCode Problems:
1. Reverse Linked List (LeetCode #206)
https://blog.algomaster.io/p/15-leetcode-patterns 7/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
6. Monotonic Stack
Use this pattern for problems that require finding the next greater or smaller
element.
Sample Problem:
Find the next greater element for each element in an array. Output -1 if the greater
element doesn’t exist.
Example:
Explanation:
1. Use a stack to keep track of elements for which we haven't found the next
greater element yet.
2. Iterate through the array, and for each element, pop elements from the stack
until you find a greater element.
https://blog.algomaster.io/p/15-leetcode-patterns 8/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
3. If the stack is not empty, set the result for index at the top of the stack to current
element.
LeetCode Problems:
1. Next Greater Element I (LeetCode #496)
The Top 'K' Elements pattern finds the top k largest or smallest elements in an array
or stream of data using heaps or sorting.
Sample Problem:
Find the k-th largest element in an unsorted array.
Example:
https://blog.algomaster.io/p/15-leetcode-patterns 9/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Output: 5
Explanation:
1. Use a min-heap of size k to keep track of the k largest elements.
3. If the heap size exceeds k, remove the smallest element from the heap.
LeetCode Problems:
1. Kth Largest Element in an Array (LeetCode #215)
8. Overlapping Intervals
In an interval array sorted by start time, two intervals [a, b] and [c, d] overlap if
b >= c (i.e., the end time of the first interval is greater than or equal to the start
time of the second interval).
https://blog.algomaster.io/p/15-leetcode-patterns 10/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Sample Problem:
Problem Statement: Merge all overlapping intervals.
Example:
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Explanation:
1. Sort the intervals by their start time.
3. Iterate through the intervals and check if it overlaps with the last interval in the
merged list.
4. If it overlaps, merge the intervals by updating the end time of the last interval in
merged.
5. If it does not overlap, simply add the current interval to the merged list.
LeetCode Problems:
1. Merge Intervals (LeetCode #56)
https://blog.algomaster.io/p/15-leetcode-patterns 11/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
The Modified Binary Search pattern adapts binary search to solve a wider range of
problems, such as finding elements in rotated sorted arrays.
Use this pattern for problems involving sorted or rotated arrays where you need to
find a specific element.
Sample Problem:
Find an element in a rotated sorted array.
Example:
Output: 4
Explanation:
1. Perform binary search with an additional check to determine which half of the
array is sorted.
2. We then check if the target is within the range of the sorted half.
LeetCode Problems:
1. Search in Rotated Sorted Array (LeetCode #33)
https://blog.algomaster.io/p/15-leetcode-patterns 12/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Binary Tree Traversal involves visiting all the nodes in a binary tree in a specific
order.
Sample Problem:
Problem Statement: Perform inorder traversal of a binary tree.
Example:
Output: [1, 3, 2]
Explanation:
1. Inorder traversal visits nodes in the order: left, root, right.
LeetCode Problems:
1. PreOrder → Binary Tree Paths (LeetCode #257)
2. InOrder → Kth Smallest Element in a BST (LeetCode #230)
https://blog.algomaster.io/p/15-leetcode-patterns 13/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Depth-First Search (DFS) is a traversal technique that explores as far down a branch
as possible before backtracking.
Use this pattern for exploring all paths or branches in graphs or trees.
Sample Problem:
Find all paths from the root to leaves in a binary tree.
Example:
Explanation:
1. Use recursion or a stack to traverse each path from the root to the leaves.
LeetCode Problems:
1. Clone Graph (LeetCode #133)
https://blog.algomaster.io/p/15-leetcode-patterns 14/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Breadth-First Search (BFS) is a traversal technique that explores nodes level by level
in a tree or graph.
Use this pattern for finding the shortest paths in unweighted graphs or level-order
traversal in trees.
Sample Problem:
Perform level-order traversal of a binary tree.
Example:
Explanation:
1. Use a queue to keep track of nodes at each level.
2. Traverse each level and add the children of the current nodes to the queue.
LeetCode Problems:
1. Binary Tree Level Order Traversal (LeetCode #102)
https://blog.algomaster.io/p/15-leetcode-patterns 15/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Use this pattern for problems involving traversing 2D grids or matrices horizontally,
vertically or diagonally.
Sample Problem:
Perform flood fill on a 2D grid. Change all the cells connected to the starting cell to
new color.
Example:
Output: [[2,2,2],[2,2,0],[2,0,1]]
https://blog.algomaster.io/p/15-leetcode-patterns 16/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Explanation:
1. Use DFS or BFS to traverse the matrix starting from the given cell.
LeetCode Problems:
1. Flood Fill (LeetCode #733)
14. Backtracking
Backtracking explores all possible solutions and backtracks when a solution path
fails.
Use this pattern when you need to find all (or some) solutions to a problem that
satisfies given constraints. For example: combinatorial problems, such as generating
permutations, combinations, or subsets.
Sample Problem:
https://blog.algomaster.io/p/15-leetcode-patterns 17/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Example:
Explanation:
1. Use recursion to generate permutations.
2. For each element, include it in the current permutation and recursively generate
the remaining permutations.
LeetCode Problems:
1. Permutations (LeetCode #46)
https://blog.algomaster.io/p/15-leetcode-patterns 18/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Use this pattern for problems with overlapping subproblems and optimal
substructure.
DP itself has multiple sub-patterns. Some of the most important ones are:
Fibonacci Numbers
0/1 Knapsack
Subset Sum
Example:
Input: n = 5
Explanation:
1. Use a bottom-up approach to calculate the n-th Fibonacci number.
2. Start with the first two numbers (0 and 1) and iterate to calculate the next
numbers like (dp[i] = dp[i - 1] + dp[i - 2]).
LeetCode Problems:
1. Climbing Stairs (LeetCode #70)
https://blog.algomaster.io/p/15-leetcode-patterns 19/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
If you found it valuable, hit a like ❤️ and consider subscribing for more such content
every week.
Ashish
https://blog.algomaster.io/p/15-leetcode-patterns 20/21
9/15/24, 4:37 PM LeetCode was HARD until I Learned these 15 Patterns
Previous Next
20 Comments
Write a comment...
18 more comments...
https://blog.algomaster.io/p/15-leetcode-patterns 21/21