LeetCode was HARD until I Learned these 15 Patterns
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.
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]
.