KatInterview

303. Range Sum Query - Immutable

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a data structure that, after being initialized with an array nums, can quickly answer multiple queries for the sum of a subarray nums[left...right]. The key constraints are the high number of potential sumRange calls and the fact that the input array nums is immutable. A naive approach of re-calculating the sum for each query by iterating from left to right would be too slow, potentially leading to a "Time Limit Exceeded" error, as the total complexity could reach O(num_queries * array_length).

Solution

Range Sum Query - Immutable in Python

class NumArray:

    def __init__(self, nums: List[int]):
        # The prefix_sum list will store the cumulative sums.
        # self.prefix_sum[i] stores the sum of nums[0]...nums[i-1].
        # The size is len(nums) + 1 to make calculations easier, with prefix_sum[0] = 0.
        self.prefix_sum = [0] * (len(nums) + 1)
        for i in range(len(nums)):
            self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i]

    def sumRange(self, left: int, right: int) -> int:
        # The sum of elements from index left to right (inclusive) is the difference
        # between the cumulative sum up to right and the cumulative sum up to left-1.
        # sum(left, right) = prefix_sum[right+1] - prefix_sum[left]
        return self.prefix_sum[right + 1] - self.prefix_sum[left]


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)

Range Sum Query - Immutable in Java

class NumArray {
    // Array to store the prefix sums.
    private int[] prefixSum;

    public NumArray(int[] nums) {
        int n = nums.length;
        // Initialize prefixSum array with size n + 1. 
        // prefixSum[0] is 0 by default for a new int array.
        // prefixSum[i] will store the sum of the first i elements of nums.
        prefixSum = new int[n + 1];
        
        // Calculate prefix sums.
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }
    }
    
    public int sumRange(int left, int right) {
        // The sum of elements from index left to right (inclusive) is
        // the sum of elements up to right minus the sum of elements up to left-1.
        // This corresponds to prefixSum[right + 1] - prefixSum[left].
        return prefixSum[right + 1] - prefixSum[left];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(left,right);
 */

Range Sum Query - Immutable in C++

class NumArray {
private:
    // Vector to store the prefix sums.
    std::vector<int> prefixSum;

public:
    NumArray(vector<int>& nums) {
        int n = nums.size();
        // Initialize prefixSum array with size n + 1. prefixSum[0] is 0.
        // prefixSum[i] will store the sum of the first i elements of nums.
        prefixSum.resize(n + 1, 0);
        
        // Calculate prefix sums.
        for (int i = 0; i < n; ++i) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }
    }
    
    int sumRange(int left, int right) {
        // The sum of elements from index left to right (inclusive) is
        // the sum of elements up to right minus the sum of elements up to left-1.
        // This corresponds to prefixSum[right + 1] - prefixSum[left].
        return prefixSum[right + 1] - prefixSum[left];
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * int param_1 = obj->sumRange(left,right);
 */

Range Sum Query - Immutable in TypeScript

class NumArray {
    // Array to store the prefix sums.
    private prefixSum: number[];

    constructor(nums: number[]) {
        const n = nums.length;
        // Initialize prefixSum array with size n + 1 and fill with 0s.
        // this.prefixSum[i] will store the sum of the first i elements of nums.
        this.prefixSum = new Array(n + 1).fill(0);

        // Calculate prefix sums.
        for (let i = 0; i < n; i++) {
            this.prefixSum[i + 1] = this.prefixSum[i] + nums[i];
        }
    }

    sumRange(left: number, right: number): number {
        // The sum of elements from index left to right (inclusive) is
        // the sum of elements up to right minus the sum of elements up to left-1.
        // This corresponds to prefixSum[right + 1] - prefixSum[left].
        return this.prefixSum[right + 1] - this.prefixSum[left];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * var obj = new NumArray(nums)
 * var param_1 = obj.sumRange(left,right)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.