Skip to content
Learn Netverks

Lesson

Step 15/36 42% through track

prefix-sums

Prefix sums

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Prefix sums: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Teams apply Prefix sums in every serious DSA project—skipping it leaves blind spots in analysis and reviews.

You will apply Prefix sums in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

A prefix sum array stores cumulative totals so range sum [l, r] is O(1) after O(n) preprocessing—foundation for subarray sum queries and 2D grid problems.

Definition

prefix[0] = 0, prefix[i+1] = prefix[i] + a[i]. Sum l..r = prefix[r+1] - prefix[l].

Build and query

#include 
#include 

int main() {
    std::vector a = {1, 2, 3, 4};
    std::vector pre(a.size() + 1, 0);
    for (size_t i = 0; i < a.size(); ++i)
        pre[i + 1] = pre[i] + a[i];
    int l = 1, r = 2; // inclusive indices on a
    int rangeSum = pre[r + 1] - pre[l];
    std::cout << "sum[" << l << ".." << r << "] = " << rangeSum << "\n";
    return 0;
}

Use cases

  • Count subarrays with sum k (with hash map)
  • Equilibrium index problems
  • 2D prefix for matrix region sums

Important interview questions and answers

  1. Q: Space cost?
    A: O(n) extra for prefix array—trade memory for O(1) range queries.
  2. Q: Off-by-one?
    A: Define whether prefix[i] sums first i elements or through i—stay consistent in interviews.

Self-check

  1. How compute sum from index l to r with prefix array?
  2. What is preprocessing time for prefix sums?

Pitfall: Off-by-one on prefix indices—define whether pre[i] sums first i elements.

Interview prep

Range sum?

pre[r+1] - pre[l] in O(1) after O(n) build.

Space?

O(n) prefix array.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Range sum O(1)?
  • Build cost?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump