#303

Range Sum Query - Immutable

Easy
ArrayDesignPrefix SumPrefix SumArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a prefix sum array allows us to compute the sum of any subarray in constant time after an initial setup phase. This is efficient for handling multiple queries.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a prefix sum array where each element at index i contains the sum of the elements from the start of the array to index i.
  2. 2Step 2: For each sumRange query, compute the sum using the prefix sums: sum = prefix[right + 1] - prefix[left].
  3. 3Step 3: Return the computed sum.
solution.py7 lines
1class NumArray:
2    def __init__(self, nums):
3        self.prefix = [0] * (len(nums) + 1)
4        for i in range(len(nums)):
5            self.prefix[i + 1] = self.prefix[i] + nums[i]
6    def sumRange(self, left: int, right: int) -> int:
7        return self.prefix[right + 1] - self.prefix[left]

Complexity note: The time complexity for building the prefix sum array is O(n), and each query is O(1), making it efficient for multiple queries.

  • 1Using a prefix sum array drastically reduces the time complexity for multiple queries.
  • 2Understanding the difference between a brute force and an optimized approach is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.