Algo-Sim › Arrays & Hashing

Range Sum Query - Immutable

Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Answer many "sum of nums[left..right]" queries in O(1) each by precomputing prefix sums.

Problem

Design a class that is built once from an integer array nums and then answers many queries sumRange(left, right): the sum of nums[left] through nums[right], inclusive. The array never changes.

Constraints

Edge cases to test

Follow-up questions

What if the array can change between queries?
Use a Fenwick tree or a segment tree: O(log n) per update and per query (LC 307).
What about sums over a 2D submatrix?
2D prefix sums with inclusion–exclusion: O(mn) to build, O(1) per query (LC 304).

Solution

Java

class NumArray {
    private final int[] prefix;

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

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

Python

class NumArray:
    def __init__(self, nums):
        self.prefix = [0] * (len(nums) + 1)
        for i in range(len(nums)):
            self.prefix[i + 1] = self.prefix[i] + nums[i]

    def sumRange(self, left, right):
        return self.prefix[right + 1] - self.prefix[left]

C++

#include <bits/stdc++.h>
using namespace std;

class NumArray {
  public:
    vector<int> prefix;

    NumArray(vector<int> &nums) {
        prefix = vector<int>(int(nums.size()) + 1);
        for (int i = 0; i < int(nums.size()); i++) {
            prefix[i + 1] = prefix[i] + nums[i];
        }
    }

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

More Arrays & Hashing problems