Skip to the solution
EasyDSA10 min read

What is the prefix sum technique?

1.2k views

The problem

Question presented to candidate: "What is the prefix sum technique? Explain it, then write Python code that preprocesses a list so that any range-sum query takes constant time."

What a strong answer should cover:

  • Definition: prefix[i] is the sum of the first i elements; with a leading 0, the range l..r is prefix[r + 1] - prefix[l].
  • Cost: O(n) to build, O(1) per query; O(n + q) instead of O(nยทq) for q queries.
  • When to use it (static array, subarray-sum problems) and when not (frequent updates: Fenwick or segment tree).
  • Extensions: 2D prefix sums with inclusion-exclusion; difference arrays for range updates.
  • Python specifics: itertools.accumulate (with initial=0), list comprehensions for 2D tables, ints never overflow.

Code / implementation expected: Yes โ€” build and query functions in Python.

  • dsa
  • prefix-sum
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBuild a prefix array and answer range queries
Python2D prefix sums for rectangle queries
PythonDifference array for range updates

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 2 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How does binary search work and what are its requirements?

Continue