Prefix Sum
Lesson 11Beginner42 minAssessment-backed

Prefix Sum

Precompute cumulative state to answer repeated range questions without rescanning the same data.

What you will be able to do

Explain prefix sum as precomputed cumulative state.
Answer repeated range-sum queries in O(1) after O(n) preprocessing.
Apply prefix sums to analytics, billing, dashboards, and time-series features.
Recognize when update-heavy data makes simple prefix sums less appropriate.

Prefix sum is the first major precomputation pattern. When a system asks many range questions over mostly stable data, you pay one linear build cost so each future range answer is just a subtraction.

Why Prefix Sum Exists

If a dashboard asks for revenue from day 10 to day 90, scanning those days is fine once. If it asks thousands of overlapping range questions, repeated scans waste work. Prefix sums store cumulative totals so each range can be answered from two stored values.

Repeated range queries answered by prefix differences
Prefix sums trade memory for faster repeated queries. The trade-off is only worth it when queries repeat or latency matters.
StepCostMeaning
Build prefixO(n)Compute cumulative totals once.
Query rangeO(1)Subtract prefix before range from prefix at range end.
MemoryO(n)Store one cumulative value per position.
Point updateO(n) for simple prefixLater prefix values become stale.

Scenario: Billing Usage Ranges

A SaaS billing page shows usage for arbitrary date ranges: last 7 days, billing month, custom export window, and per-team reporting. If the usage array is stable for the rendered period, prefix sums make these range totals fast and predictable.

Same Pattern in Java, Python, and JavaScript

class PrefixSum {
    private final long[] prefix;

    PrefixSum(int[] values) {
        prefix = new long[values.length + 1];
        for (int i = 0; i < values.length; i++) {
            prefix[i + 1] = prefix[i] + values[i];
        }
    }

    long rangeSum(int left, int rightInclusive) {
        return prefix[rightInclusive + 1] - prefix[left];
    }
}

Assessment trap

Prefix sums are not automatically best. If values update frequently and queries interleave with updates, simple prefix arrays become expensive to maintain. Later modules introduce trees for that case.

Field judgmentEngineering Notes

  • Use prefix sums for repeated range queries over stable data.
  • Prefer a leading zero prefix to simplify boundaries.
  • State build time, query time, and memory cost.
  • Mention update cost when data changes.
  • Prefix ideas generalize to counts, balances, and cumulative constraints.

Interview signalFrequently Asked Interview Questions

These are canonical interview patterns for this topic, phrased as concrete problem statements. They avoid vague theory questions and prepare you for the exact reasoning interviewers expect: invariant, edge cases, complexity, and trade-off.

  • Build a structure that answers repeated inclusive range-sum queries in O(1).
  • Count how many contiguous subarrays sum to k.
  • Given daily active-user counts, answer many custom date-range total queries.

Production practiceCompany-Style Practice Examples

These are not claimed as exact company-specific questions. They are the interview patterns repeatedly used by product companies to test whether you can move from brute force to a defensible implementation.

ExampleBrute-force approachStronger solutionProduction notes
Range sum queryRescan the requested range each time.Build prefix once and answer with subtraction.Great for repeated reads over stable data.
Subarray sum equals kCheck all subarrays.Use running prefix sum plus map of previous sums.This extends prefix logic beyond static range queries.
Analytics dashboardCompute custom date totals on every render.Precompute cumulative daily metrics.Mention updates and stale cache handling.

Solved modelInterview Question Solutions

Question 1: Range Sum Query

Build a structure that answers repeated inclusive range-sum queries in O(1). Build prefix with a leading zero. The sum from left to right is prefix[right + 1] minus prefix[left].

class PrefixSum {
    private final long[] prefix;

    PrefixSum(int[] values) {
        prefix = new long[values.length + 1];
        for (int i = 0; i < values.length; i++) prefix[i + 1] = prefix[i] + values[i];
    }

    long rangeSum(int left, int right) {
        return prefix[right + 1] - prefix[left];
    }
}

Question 2: Subarray Sum Equals K

Count how many contiguous subarrays sum to k. Track running prefix sums. If running - k appeared before, every previous occurrence forms a valid subarray ending here.

import java.util.*;

class SubarraySumK {
    static int count(int[] nums, int k) {
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, 1);
        int running = 0;
        int answer = 0;
        for (int value : nums) {
            running += value;
            answer += seen.getOrDefault(running - k, 0);
            seen.put(running, seen.getOrDefault(running, 0) + 1);
        }
        return answer;
    }
}

Question 3: Product Analytics Date Ranges

Given daily active-user counts, answer many custom date-range total queries. This is a direct prefix-sum application. Build once for the stable date range, then answer each query with two prefix reads.

class DailyTotals {
    private final long[] prefix;

    DailyTotals(int[] dailyCounts) {
        prefix = new long[dailyCounts.length + 1];
        for (int day = 0; day < dailyCounts.length; day++) {
            prefix[day + 1] = prefix[day] + dailyCounts[day];
        }
    }

    long totalUsers(int startDay, int endDay) {
        return prefix[endDay + 1] - prefix[startDay];
    }
}

Solved modelWorked Interview Answer

Build a structure that answers repeated inclusive range-sum queries in O(1). A leading zero makes boundaries simple: sum(left, right) = prefix[right + 1] - prefix[left].

class PrefixSum {
    private final long[] prefix;

    PrefixSum(int[] values) {
        prefix = new long[values.length + 1];
        for (int i = 0; i < values.length; i++) prefix[i + 1] = prefix[i] + values[i];
    }

    long rangeSum(int left, int right) {
        return prefix[right + 1] - prefix[left];
    }
}

Hands-on drillTry It Yourself

Practice task

Given daily usage values, build a prefix array with a leading zero and answer three custom date-range totals using subtraction.

Failure patternsCommon Mistakes to Avoid

  • Off-by-one errors in inclusive range queries.
  • Forgetting the O(n) memory cost.
  • Using simple prefix sums when updates and queries are heavily interleaved.

Execution guardrailQuick-Start Checklist

  • Add a leading zero prefix.
  • Define whether ranges are inclusive or exclusive.
  • Use prefix[right + 1] - prefix[left].
  • State build, query, and memory costs.
  • Discuss update frequency.

Recall drillKnowledge Check

QuestionStrong answer
What is the build cost?O(n).
What is the range query cost after build?O(1).
What trade-off does prefix sum make?Extra memory and upfront build for faster repeated range reads.

VocabularyKey Terms

TermMeaning
PrefixCumulative value up to a position.
Range queryA question about a contiguous segment.
PrecomputationDoing work upfront to make later queries cheaper.

Next practiceFurther Reading

  • Study subarray sum problems with hash maps.
  • Review two-dimensional prefix sums for grids.
  • Learn Fenwick trees and segment trees for update-heavy cases later.