Range Sum Query - Immutable — LeetCode 303 Python Solution

EasyDesignArrayPrefix Sum
Problem
#303
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums.

Example

Input
["NumArray", "sumRange", "sumRange", "sumRange"]
Output
[null, 1, -1, -3]
Explanation
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);

Python solution

Python
class NumArray:
    def __init__(self, nums: List[int]):
        self.s = list(accumulate(nums, initial=0))

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


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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 303. Range Sum Query - Immutable is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 303. Range Sum Query - Immutable?
LeetCode 303. Range Sum Query - Immutable is rated Easy on LeetCode.
What is the time complexity of LeetCode 303. Range Sum Query - Immutable?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 303. Range Sum Query - Immutable?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 303. Range Sum Query - Immutable cover?
LeetCode 303. Range Sum Query - Immutable is tagged Design, Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview