AlgoMaster Logo

Range Sum Query - Immutable

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The simplest way to solve this problem is to calculate the sum of elements from i to j every time a query is made.

Intuition:

  • For each query, loop through the range from i to j and sum up the elements.
  • This approach is straightforward but not efficient for large numbers of queries or larger input sizes.

Code:

2. Prefix Sum

A more optimal approach is to preprocess the input array to create a prefix sum array.

Intuition:

  • The prefix sum at each index i stores the cumulative sum of the array from 0 to i.
  • For a query to get the sum from index i to j, we can use the formula: [ \text{sumRange}(i, j) = \text{prefixSum}[j] - \text{prefixSum}[i-1] ]
  • This reduces the time complexity of each query to O(1).

Steps:

  1. Initialize a prefix sum array with an extra zero at the start for ease of calculation.
  2. For each element in the input array, calculate the cumulative sum and store it in the prefix sum array.
  3. When a query is made, use the formula above to get the sum in constant time.

Code: