AlgoViz

Prefix sums

medium 20 min

Write the running totals of an array into P once, with P[0] = 0, and the sum of any range a[l..r] becomes one subtraction, P[r + 1] - P[l].

Where it shows up

The same pattern appears across everyday software.

  • Analytics dashboards and running totals

    Databases compute cumulative sums with window functions (SUM(...) OVER (ORDER BY day)) so that 'revenue between two dates' is a difference of two stored totals. Time-series stores keep similar rollups to answer range queries without scanning every point.

  • Integral images in computer vision

    A summed-area table is a 2D prefix sum over pixel values. The Viola-Jones face detector uses it to sum any rectangle of pixels in four reads, which made real-time detection possible on early hardware. Box blurs and adaptive thresholding use the same table.

  • Fitness and usage counters

    Step counters, phone screen-time reports and API usage meters store running totals per day or per minute. 'This week', 'since Tuesday' and 'the last 30 days' are then each one subtraction.

  • Scheduling, bookings and load

    Hotel and meeting-room bookings, ride sharing and network bandwidth reservations add a load over a time range. A difference array marks each start and end, and one sweep gives the load at every moment: the car pooling problem in production.

  • Genomics and text statistics

    Counting G and C bases in any window of a DNA sequence, or how often a character occurs in any slice of a long string, uses one prefix count array per symbol. Each window question is then O(1) instead of a rescan.