Data Structures19 sections · 729 units
Open in Course

The Core Idea

Subtraction trick

Here's why prefix sums work. The sum from index ll to rr equals: sum(l,r)=prefix[r+1]prefix[l]sum(l, r) = prefix[r+1] - prefix[l] Think about it: prefix[r+1]prefix[r+1] contains everything from 00 to rr.

Subtracting prefix[l]prefix[l] removes everything from 00 to l1l-1. What's left is exactly the sum from ll to rr. Two array lookups and one subtraction. That's O(1)O(1) per query, no matter how big the range.