Range Sum Query - Immutable — LeetCode 303 Python Solution
- Problem
- #303
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.