Back to Academy
patterns
Prefix Sum
Prefix sum precomputes cumulative sums so that any subarray sum can be answered in O(1) time. By storing the running total at each index, the sum of elements from index i to j equals prefix[j+1] - prefix[i]. This transforms repeated range-sum queries from O(n) each to O(1) after an O(n) preprocessing step.
Use Cases
- •Answering multiple range sum queries efficiently
- •Finding subarrays that sum to a given target
- •Computing running averages and cumulative statistics
Complexity Analysis
| Metric | Best | Average | Worst |
|---|---|---|---|
| Time | O(n) | O(n) | O(n) |
| Space | O(n) | ||
Visualization
Implementation
Output
Click "Run Code" to see output...