Katkat

Compute Range Sum Quickly

MetaSoftware Engineer · Technical Screen

Last updated

This question tests the ability to trade preprocessing time for query performance using prefix sum arrays to efficiently calculate the sum of elements within a specified range.

Problem Statement

Design a class RangeSumQuery that supports calculating the sum of elements in an array between two indices i and j (inclusive). Your implementation must be optimized for multiple queries on the same array.

Requirements

  • The class should be initialized with an integer array nums.
  • Implement a method sumRange(i, j) that returns the sum of elements from index i to index j (where 0 <= i <= j < n).

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • The number of sumRange calls can be up to 10^5.

Example

# Initialization
nums = [-2, 0, 3, -5, 2, -1]
obj = RangeSumQuery(nums)

# Query operations
obj.sumRange(0, 2) # returns 1 (-2 + 0 + 3)
obj.sumRange(2, 5) # returns -1 (3 + -5 + 2 + -1)
obj.sumRange(0, 5) # returns -3

Edge Cases

  • Queries covering the entire array (start index 0, end index length-1).
  • Queries covering a single element (i == j).
  • Arrays containing negative numbers.

Hints

Hint 1

Consider precomputing a running total of the array elements to avoid iterating through the array for every query.

Hint 2

If you store the cumulative sum at each index `k` as the sum of all elements from index `0` to `k`, how can you derive the sum of a sub-segment `[i, j]` using only two of these values?

Hint 3

A prefix sum array of size `n+1` (where the first element is 0) can simplify the math for boundary conditions like `i=0`.

Follow-up questions

  • How would you modify your design if the input array `nums` were mutable and elements could be updated frequently?
  • What is the space complexity of your current solution, and can it be optimized if you are memory-constrained?
  • How would you adapt this approach to perform 2D range sum queries on a matrix?