KatInterview

Static Array Range Sum Queries

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashingarraysprefix-sumdata-structures

Last updated

Process a sequence of range sum queries on an immutable array efficiently using prefix sums.

Given an integer array nums and a sequence of range queries, return the sum of the elements for each specified range query.

You are given:

  • An initial list of integers nums.
  • A list of operation names operations.
  • A matching list of argument pairs arguments.

For each query operation in operations named "sumRange", the corresponding entry in arguments is a pair of indices [left, right]. Calculate the sum of the subarray from index left to right inclusive (i.e., $\sum_{k=left}^{right} \text{nums}[k]$).

If an operation in operations is not "sumRange" (such as constructor calls), the output for that operation position should be None (represented as null in JSON).

Your solution should be optimized to answer multiple range sum queries efficiently.

Constraints

  • $1 \le \text{len}(nums) \le 10^5$
  • $-10^4 \le nums[i] \le 10^4$
  • $1 \le \text{len}(operations) \le 10^5$
  • $\text{len}(operations) == \text{len}(arguments)$
  • For each "sumRange" query, $0 \le left \le right < \text{len}(nums)$.

Examples

Example 1

Input: range_sum_query([-2, 0, 3, -5, 2, -1], [17, 17, 17], [[0, 2], [2, 5], [0, 5]])

Output: [None, None, None]

Hints

Hint 1

Iterating through the range [left, right] for every query takes O(N) per query, which will be too slow for many operations.

Hint 2

Can you precompute running totals so that any subarray sum can be calculated in O(1) time?

Hint 3

Compute an array `prefix` of size N + 1 where `prefix[k]` stores the sum of the first `k` elements. How can `prefix[right + 1]` and `prefix[left]` give you the subarray sum?