Back to 20 Concepts
optimizationIntermediate

Prefix Sums & O(1) Range Queries

A Prefix Sum array precomputes cumulative totals: P[i] = P[i-1] + arr[i]. Any range sum query sum(L, R) is answered in O(1) time via P[R] - P[L-1].

Intuitive Mental Model

The Mileage Markers on a Highway: Marker at Mile 50 and Mile 120. Distance between them = 120 - 50 = 70 miles in a single subtraction without measuring each road segment.

C / TypeScript ImplementationHardware & Algorithmic Standard
class PrefixSum {
  prefix: number[];
  constructor(nums: number[]) {
    this.prefix = [0];
    for (let i = 0; i < nums.length; i++) {
      this.prefix.push(this.prefix[i] + nums[i]);
    }
  }
  query(L: number, R: number): number {
    return this.prefix[R + 1] - this.prefix[L]; // O(1) instant range sum!
  }
}

Key Architectural Takeaways

  • O(1) Range Queries: Reduces Q range queries from O(Q * N) down to O(Q + N).
  • Difference Array: Allows range updates arr[L..R] += V in O(1) time.
Common Coding Mistake

Off-by-one errors with array bounds when L = 0.

Optimal Solution

Use a 1-indexed prefix array with prefix[0] = 0.