← Questions
Range sum query (immutable)
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Feb 2026. It tests prefix sums and design.
Preprocess an integer array once so that the sum of any range nums[i..j] (inclusive) can be answered in constant time. The array never changes after construction, and many queries follow.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
RangeSum(nums: list[int])— preprocesses the array. -
sum_range(i: int, j: int) -> int— the sum ofnums[i]throughnums[j], with0 <= i <= j < len(nums).
Example
r = RangeSum([-2, 0, 3, -5, 2, -1])
r.sum_range(0, 2) -> 1
r.sum_range(2, 5) -> -1
r.sum_range(0, 5) -> -3
Constraints
-
1 <= len(nums) <= 10^4;-10^5 <= nums[k] <= 10^5. - Up to
10^4calls tosum_range.
Clarifying questions
- Are the bounds inclusive, and always valid?
- Can the array change after construction?
- How many queries compared with the array length? That decides whether preprocessing pays off.
- Can sums overflow 32 bits?
What a strong answer covers
- A prefix array of length
n + 1withprefix[0] = 0andprefix[k + 1] = prefix[k] + nums[k]; thensum_range(i, j) = prefix[j + 1] - prefix[i].O(n)build,O(1)per query,O(n)space. - Why the leading zero removes the special case for
i = 0. - A reusable design: the prefix array built once in the constructor, not per call.
- Tests: a single-element range, the whole array, negative values.
Follow-ups
- The array also receives point updates: use a Fenwick tree or segment tree for
O(log n)updates and queries. - The same for a 2D matrix: sums of any sub-rectangle in
O(1). - Count the subarrays whose sum equals
kusing the same prefix idea.
Where it's asked
- Meta · Technical phone screen · Last asked Feb 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
prefix sums · design
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
