Search⌘ K
AI Features

Solution: Range Sum Query - Immutable

Explore how to efficiently compute the sum of array elements within a given range by using an immutable prefix sum approach. This lesson guides you through implementing the NumArray class that precomputes cumulative sums to enable constant-time sumRange queries, helping you solve complex coding challenges with optimal time and space complexity.

Statement

You are given an integer array, nums, and you need to handle multiple queries of the following type:

  • Query: Calculate the sum of elements in nums between indices i and j (inclusive), where i <= j.

Implement the NumArray class to support the following operations efficiently:

  • Constructor: Initializes the object with the integer array nums.

  • sumRange(i, j): Returns the sum of the elements of nums between indices i and j (inclusive), i.e., the sum of nums[i] + nums[i + 1] + ... + nums[j].

Constraints:

  • 11 \leq nums.length 103\leq 10^3

  • 105-10^5 \leq nums[i] ...