Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

303. Range Sum Query - Immutable

Explanation:

To efficiently handle multiple sum range queries, we can pre-compute the cumulative sum of the input array nums and store it in an auxiliary array prefixSum. This prefixSum array will help us calculate the sum of elements between any two indices left and right by just looking up the values at prefixSum[right] and prefixSum[left-1] (if left > 0).

The algorithm involves initializing the prefixSum array by iterating through the input array nums and calculating the cumulative sum up to each index. Then, for each sumRange query, we can return the difference between prefixSum[right] and prefixSum[left-1] if left > 0, or prefixSum[right] if left == 0.

  • Time complexity: O(n) for initialization and O(1) for each sum range query
  • Space complexity: O(n) to store the prefixSum array

:

class NumArray {
    private int[] prefixSum;

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

    public int sumRange(int left, int right) {
        if (left == 0) {
            return prefixSum[right];
        }
        return prefixSum[right] - prefixSum[left - 1];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.