← Questions

Range sum query (immutable)

0
MetaCodingLast asked Feb 2026

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 of nums[i] through nums[j], with 0 <= 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^4 calls to sum_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 + 1 with prefix[0] = 0 and prefix[k + 1] = prefix[k] + nums[k]; then sum_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 k using 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

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