VOOZH about

URL: https://www.geeksforgeeks.org/dsa/range-sum-queries-without-updates/

⇱ Range sum queries without updates - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Range sum queries without updates

Last Updated : 6 Mar, 2025

Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.

Examples: 

Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5

[Naive Solution] - Simple Sum - O(n) for Every Query and O(1) Space

A Simple Solution is to compute the sum for every query.


Output

9
12

[Expected Solution] - Prefix Sum - O(1) for Every Query and O(n) Space

Follow the given steps to solve the problem:

  • Create the prefix sum array of the given input array
  • Now for every query (1-based indexing)
    • If L is greater than 1, then print prefixSum[R] - prefixSum[L-1]
    • else print prefixSum[R]

Output
9
12

Here time complexity of every range sum query is O(1) and the overall time complexity is O(n).

Auxiliary Space required = O(n), where n is the size of the given array.

The question becomes complicated when updates are also allowed. In such situations when using advanced data structures like Segment Tree or Binary Indexed Tree.

Comment