Prefix Sum is a powerful problem solving pattern that can optimize the time complexity of many array-related problems from O(n²) to O(n).
In this chapter, you'll learn:
In simple terms, a prefix sum for an array is the cumulative sum of elements from the start of the array to a given index.
In other words, each element in the prefix sum array at index i contains the sum of all elements from the start of the original array up to index i.
Here’s how to build the prefix sum:
prefix_sum array with an extra space to handle zero-based indexing:prefix_sum = [0] * (len(nums) + 1)prefix_sum[i + 1] = prefix_sum[i] + nums[i].If the input array is:
The prefix sum array will look like this:
One thing to remember is that :
Sometimes, you don't even need a new array. You can modify the original array itself and use it as a prefix sum array if memory is a constraint.
Now that we know what a prefix sum is, let’s talk about when to use this pattern.
Here are a few common scenarios:
In short, if your problem involves frequent calculations of sums over ranges or conditions over subarrays, the Prefix Sum pattern is likely the way to go.