VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-static-range-sum-queries/

⇱ CSES Solutions – Static Range Sum Queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Static Range Sum Queries

Last Updated : 23 Jul, 2025

Given an array arr[] of N integers, your task is to process Q queries of the form: what is the sum of values in range [a,b]?

Examples

Input: arr[] = {1, 3, 4, 8, 6, 1, 4, 2}, Queries: {{2, 5}, {1, 3}}
Output: 21 8
Explanation:

  • Query 1: Sum of elements from index 2 to 5 = 3 + 4 + 8 + 6 = 21
  • Query 2: Sum of elements from index 1 to 3 = 1 + 3 + 4 = 8

Input: arr[] = {3, 2, 4, 5, 1, 1, 5, 3} Queries: {{2, 4}, {5, 6}, {1, 8}, {3, 3}}
Output: 11 2 24 4
Explanation:

  • Query 1: Sum of elements from position 2 to 4 = 2 + 4 + 5 = 11
  • Query 2: Sum of elements from position 5 to 6 = 1 + 1 = 2
  • Query 3: Sum of elements from position 1 to 8 = 3 + 2 + 4 + 5 + 1 + 1 + 5 + 3 = 24
  • Query 4: Sum of elements from position 3 to 3 = 4

Algorithm: To solve the problem, follow the below idea:

We can solve this problem using Prefix Sum approach.

  • Pre-processing: Compute prefix sums for the array.
  • Query Processing: Find the sum of the elements between the range l and r , i.e. prefixSum[r] - prefixSum[l-1].

Step-by-step algorithm:

  • Create a prefix sum array prefixSum of the size n+1, where n is the size of input array.
  • Initialize prefixSum[0] to 0 and compute prefixSum[i] = prefixSum[i-1] + array[i-1] for i from 1 to n.
  • To answer a query [l, r] return prefixSum[r+1] - prefixSum[l].

Below is the implementation of the algorithm:


Output
11 2 24 4 

Time Complexity : O(N + Q), where N is the number of elements in arr[] and Q is the number of queries.
Auxiliary Space: O(N)

Comment