You just learned running sums. Now let's unlock their superpower: answering range sum queries in O(1) time. Yes, constant time. No matter how big the array. 🤯
Imagine a huge spreadsheet with 1 million rows of sales data. Your boss asks: "What's the total sales from row 500 to row 800?" Then five minutes later: "Now rows 100 to 950?" Then again. And again. If you add up numbers each time, that's painful. But if you have a running total column... you just subtract two numbers. Boom. Instant answer. 📊
That running total column? That's a prefix sum array.
Step 1: Build it. Given nums = [2, 4, 3, 3, 5]:
Step 2: Use it. Want the sum from index i to j?
i == 0: the answer is just prefix[j] (it already holds the sum from the start!)i > 0: the answer is prefix[j] - prefix[i - 1] (total up to j, minus the part before i)Let's trace through with prefix = [2, 6, 9, 12, 17]:
sum(1..3) = prefix[3] - prefix[0] = 12 - 2 = 10 ✓ (that's 4+3+3)sum(0..4) = prefix[4] = 17 ✓ (entire array)sum(2..2) = prefix[2] - prefix[1] = 9 - 6 = 3 ✓ (just the element at index 2)Why is this so powerful? Build the prefix array once in O(n), then answer unlimited range queries in O(1) each. Without it, every query costs O(n). With 1000 queries on a million-element array, that's the difference between 1 million operations and 1 billion. 💡
Prefix vs. Suffix: A prefix array builds from left to right. A suffix array builds from right to left. In the next exercise (Product Except Self), you'll use both — a prefix product and a suffix product. This exercise lays that foundation! 🧱
This concept appears everywhere in competitive programming and interviews. Master it here, and a whole family of problems opens up. Let's build it! 🔨
def build_prefix_sum(nums):
prefix = [nums[0]]
for i in range(1, len(nums)):
prefix.append(prefix[-1] + nums[i])
return prefix
def range_sum(prefix, i, j):
if i == 0:
return prefix[j]
return prefix[j] - prefix[i - 1]
nums = [2, 4, 3, 3, 5]
prefix = build_prefix_sum(nums)
print(f"Prefix: {prefix}")
print(f"Sum [1..3]: {range_sum(prefix, 1, 3)}")
print(f"Sum [0..4]: {range_sum(prefix, 0, 4)}")
print(f"Sum [2..2]: {range_sum(prefix, 2, 2)}")