0
0
DSA Pythonprogramming

Prefix Sum Array in DSA Python

Choose your learning style9 modes available
Mental Model
A prefix sum array stores sums of elements from the start up to each position, so we can quickly find sums of any part of the original array.
Analogy: Imagine a row of buckets where each bucket holds the total water collected from the first bucket up to that bucket. To find water between two buckets, just subtract the totals.
Original array:  [2] -> [4] -> [6] -> [8] -> [10]
Prefix sums:     [2] -> [6] -> [12] -> [20] -> [30]
Dry Run Walkthrough
Input: array: [2, 4, 6, 8, 10]
Goal: Create a prefix sum array to quickly find sums of any subarray
Step 1: Start prefix sum with first element same as original
Prefix sums: [2] -> null
Why: The first prefix sum is just the first element itself
Step 2: Add second element to previous prefix sum: 2 + 4 = 6
Prefix sums: [2] -> [6] -> null
Why: Each prefix sum adds current element to sum before it
Step 3: Add third element to previous prefix sum: 6 + 6 = 12
Prefix sums: [2] -> [6] -> [12] -> null
Why: Continue accumulating sums step by step
Step 4: Add fourth element to previous prefix sum: 12 + 8 = 20
Prefix sums: [2] -> [6] -> [12] -> [20] -> null
Why: Keep building the prefix sums array
Step 5: Add fifth element to previous prefix sum: 20 + 10 = 30
Prefix sums: [2] -> [6] -> [12] -> [20] -> [30] -> null
Why: Final prefix sum includes all elements
Result:
Prefix sums: [2] -> [6] -> [12] -> [20] -> [30] -> null
Annotated Code
DSA Python
class PrefixSumArray:
    def __init__(self, arr):
        self.arr = arr
        self.prefix_sums = []
        self.build_prefix_sums()

    def build_prefix_sums(self):
        if not self.arr:
            return
        self.prefix_sums.append(self.arr[0])  # start with first element
        for i in range(1, len(self.arr)):
            # add current element to last prefix sum
            self.prefix_sums.append(self.prefix_sums[i-1] + self.arr[i])

    def range_sum(self, left, right):
        # sum from left to right using prefix sums
        if left == 0:
            return self.prefix_sums[right]
        return self.prefix_sums[right] - self.prefix_sums[left - 1]

# Driver code
arr = [2, 4, 6, 8, 10]
prefix_sum_obj = PrefixSumArray(arr)
print('Prefix sums:', ' -> '.join(map(str, prefix_sum_obj.prefix_sums)) + ' -> null')
# Example: sum from index 1 to 3 (4 + 6 + 8)
sum_1_3 = prefix_sum_obj.range_sum(1, 3)
print('Sum from index 1 to 3:', sum_1_3)
self.prefix_sums.append(self.arr[0]) # start with first element
initialize prefix sums with first element of array
self.prefix_sums.append(self.prefix_sums[i-1] + self.arr[i])
add current element to previous prefix sum to build cumulative sums
if left == 0: return self.prefix_sums[right]
if sum starts from index 0, return prefix sum at right index
return self.prefix_sums[right] - self.prefix_sums[left - 1]
subtract prefix sums to get sum of subarray from left to right
OutputSuccess
Prefix sums: 2 -> 6 -> 12 -> 20 -> 30 -> null Sum from index 1 to 3: 18
Complexity Analysis
Time: O(n) because we compute prefix sums by traversing the array once
Space: O(n) because we store a prefix sum for each element in the array
vs Alternative: Without prefix sums, each subarray sum query takes O(k) time for k elements; prefix sums reduce query time to O(1) after O(n) preprocessing
Edge Cases
empty array
prefix sums remain empty, no errors occur
DSA Python
if not self.arr:
    return
single element array
prefix sums contain just that one element
DSA Python
self.prefix_sums.append(self.arr[0])  # start with first element
range sum where left equals right
returns the single element at that index correctly
DSA Python
if left == 0:
    return self.prefix_sums[right]
When to Use This Pattern
When you need to find sums of many subarrays quickly, use prefix sums to answer queries in constant time after one pass preprocessing.
Common Mistakes
Mistake: Forgetting to handle empty input array before building prefix sums
Fix: Add a check to return early if the input array is empty
Mistake: Incorrectly calculating subarray sum by not subtracting prefix sums properly
Fix: Use prefix_sums[right] - prefix_sums[left - 1] for left > 0, else prefix_sums[right]
Summary
It builds an array where each position holds the sum of all elements up to that position.
Use it when you want to quickly find sums of any part of an array multiple times.
The key insight is that sums of subarrays can be found by subtracting two prefix sums.