LeetCode 303: Range Sum Query - Immutable Solution

Master LeetCode problem 303 (Range Sum Query - Immutable), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

303. Range Sum Query - Immutable

Problem Explanation

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

:

Solution Code

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];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 303 (Range Sum Query - Immutable)?

This page provides optimized solutions for LeetCode problem 303 (Range Sum Query - Immutable) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 303 (Range Sum Query - Immutable)?

The time complexity for LeetCode 303 (Range Sum Query - Immutable) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 303 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 303 in Java, C++, or Python.

Back to LeetCode Solutions