Easy dsa arrays

Range Sum Query - Immutable

The 30 second answer

I precompute a prefix array where prefix of i plus one is the sum of the first i plus one elements. Then the sum from left to right is prefix of right plus one minus prefix of left, which is constant time per query after linear preprocessing. The extra leading zero removes the special case for left equals zero.

Could you say this in an interview?

Problem Design a class built from an integer array that answers many "sum of elements between indices left and right, inclusive" queries. The array never changes. Original: LeetCode 303: Range Sum Query - Immutable.

Understanding the prompt "Immutable" plus "many queries" is the hint to precompute once. "Inclusive" means both ends count.

Pattern recognition Many range sums on a static array is the prefix-sum pattern.

Brute force Loop from left to right for every query: O(n) per query.

Optimal Build prefix of length n+1 with prefix[0] = 0. Then sum(l, r) = prefix[r + 1] - prefix[l].

Alternatives If the array can change, use a Fenwick tree or segment tree (LeetCode 307). That is out of scope for this path's main levels.

Java solution

public class RangeSumQuery {
    private final long[] prefix;

    RangeSumQuery(int[] nums) {
        prefix = new long[nums.length + 1];
        for (int i = 0; i < nums.length; i++) prefix[i + 1] = prefix[i] + nums[i];
    }

    int sumRange(int left, int right) {
        return (int) (prefix[right + 1] - prefix[left]);
    }

    public static void main(String[] args) {
        var q = new RangeSumQuery(new int[] {-2, 0, 3, -5, 2, -1});
        System.out.println(q.sumRange(0, 2)); // 1
        System.out.println(q.sumRange(2, 5)); // -1
        System.out.println(q.sumRange(0, 5)); // -3
    }
}

Complexity O(n) preprocessing, O(1) per query, O(n) space.

Edge cases

  • left equals right: a single element.
  • left equals 0: the leading zero handles it.
  • Large totals: a long prefix avoids intermediate overflow.

Follow-ups

  • 2D version (LeetCode 304): inclusion and exclusion on a 2D prefix table.
  • Updates between queries: Fenwick tree.

Tests For [-2,0,3,-5,2,-1]: (0,2) returns 1, (2,5) returns -1, (0,5) returns -3.

How to say it in the interview "The array never changes, so I pay O(n) once to build prefix sums with a leading zero. Each query is then one subtraction, O(1)."

Sources (2)
  1. LeetCode 303: Range Sum Query - Immutableleetcode.com
  2. JLS 17, 5.1.2: Widening primitive conversiondocs.oracle.com