Documentation Index
Fetch the complete documentation index at: https://swe.aboneda.com/llms.txt
Use this file to discover all available pages before exploring further.
Prefix Sums
A technique of precomputing cumulative sums to answer range sum queries in O(1) time.Core Idea
Given an arraynums, build a prefix sum array where:
l to r:
Complexity
| Operation | Time |
|---|---|
| Build prefix array | O(n) |
| Range sum query | O(1) |
| Space | O(n) |
Variations
1D Prefix Sum
Standard cumulative sum for range queries on arrays.2D Prefix Sum
For submatrix sum queries. Uses inclusion-exclusion:Prefix XOR
Same idea but with XOR — useful for finding subarrays with target XOR.Difference Array
The inverse of prefix sums — used for efficient range updates:- Increment range
[l, r]byval:diff[l] += val,diff[r+1] -= val - Reconstruct with prefix sum
Classic Problems
- Range Sum Query (Immutable)
- Subarray Sum Equals K (prefix sum + hash map)
- Contiguous Array (prefix sum with transformation)
- Product of Array Except Self
- Range Sum Query 2D (Immutable)
- Count Number of Nice Subarrays
Pairs Well With
- Sliding Window — when window conditions involve sums
- Hash Maps — to find subarrays with a target sum in O(n)
- Binary Search — on prefix sums for threshold problems
