Prefix Sum Range Queries
Build one prefix array up front, then answer any range sum query with a single subtraction instead of re-summing the slice every time.
Code
prices = [4, 2, 7, 1, 9, 3]
# prefix[i] holds the sum of the first i items; prefix[0] stays 0
prefix = [0]
for value in prices:
prefix.append(prefix[-1] + value)
print("prefix:", prefix)
def range_sum(left, right):
"""Sum of prices[left:right] as one subtraction after the O(n) build."""
return prefix[right] - prefix[left]
print("sum [0:6]:", range_sum(0, len(prices)))
print("sum [2:5]:", range_sum(2, 5))
print("sum [4:6]:", range_sum(4, 6))
queries = [(0, 3), (1, 4), (2, 6)]
for left, right in queries:
print(f"[{left}:{right}] -> {range_sum(left, right)}")
# cross-check every query against plain slicing
print("matches slicing:", all(range_sum(l, r) == sum(prices[l:r]) for l, r in queries))Output
Captured from a sandboxed run of this snippet in the build pipeline.
prefix: [0, 4, 6, 13, 14, 23, 26]
sum [0:6]: 26
sum [2:5]: 17
sum [4:6]: 12
[0:3] -> 13
[1:4] -> 10
[2:6] -> 20
matches slicing: TrueWhat the file does
The snippet is organized around the function range_sum.
The cycling part of this snippet is for value in prices.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Using it
The surface you program against: def range_sum(left, right)
Output arrives labeled — prefix:, sum [0:6]:, sum [2:5]: — when the file runs.
Treat range_sum as the API: import it, and ignore the supporting code.
Key statements
def range_sum(left, right):
"""Sum of prices[left:right] as one subtraction after the O(n) build."""
return prefix[right] - prefix[left]
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `range_sum` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.