CSES Solutions – Static Range Sum Queries
Last Updated :
10 Apr, 2024
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:
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
// function to solve all the static range queries
vector<ll> solve(vector<ll>& arr,
vector<vector<ll> >& queries, ll n, ll q)
{
// Creating a prefix Sum Array
vector<ll> prefixSum(n + 1, 0);
for (int i = 1; i <= n; ++i) {
prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
}
// Creating Result array to store the result of each
// query
vector<ll> result;
for (auto& query : queries) {
ll l = query[0], r = query[1];
ll sum = prefixSum[r] - prefixSum[l - 1];
result.push_back(sum);
}
return result;
}
int main()
{
// Sample Input
ll n = 8, q = 4;
vector<ll> arr = { 3, 2, 4, 5, 1, 1, 5, 3 };
vector<vector<ll> > queries
= { { 2, 4 }, { 5, 6 }, { 1, 8 }, { 3, 3 } };
// Function Call
vector<ll> result = solve(arr, queries, n, q);
for (ll sum : result) {
cout << sum << " ";
}
cout << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to solve all the static range queries
public static List<Long> solve(List<Long> arr, List<List<Long>> queries, int n, int q) {
// Creating a prefix Sum Array
List<Long> prefixSum = new ArrayList<>(Collections.nCopies(n + 1, 0L));
for (int i = 1; i <= n; ++i) {
prefixSum.set(i, prefixSum.get(i - 1) + arr.get(i - 1));
}
// Creating Result array to store the result of each query
List<Long> result = new ArrayList<>();
for (List<Long> query : queries) {
long l = query.get(0), r = query.get(1);
long sum = prefixSum.get((int)r) - prefixSum.get((int)l - 1);
result.add(sum);
}
return result;
}
public static void main(String[] args) {
// Sample Input
int n = 8, q = 4;
List<Long> arr = Arrays.asList(3L, 2L, 4L, 5L, 1L, 1L, 5L, 3L);
List<List<Long>> queries = Arrays.asList(
Arrays.asList(2L, 4L),
Arrays.asList(5L, 6L),
Arrays.asList(1L, 8L),
Arrays.asList(3L, 3L)
);
// Function Call
List<Long> result = solve(arr, queries, n, q);
for (Long sum : result) {
System.out.print(sum + " ");
}
System.out.println();
}
}
Python3
# function to solve all the static range queries
def solve(arr, queries):
# Creating a prefix Sum Array
prefix_sum = [0] * (len(arr) + 1)
for i in range(1, len(arr) + 1):
prefix_sum[i] = prefix_sum[i - 1] + arr[i - 1]
# Creating Result array to store the result of each query
result = []
for query in queries:
l, r = query[0], query[1]
# Calculating sum for the current query range
sum_val = prefix_sum[r] - prefix_sum[l - 1]
result.append(sum_val)
return result
# Sample Input
arr = [3, 2, 4, 5, 1, 1, 5, 3]
queries = [[2, 4], [5, 6], [1, 8], [3, 3]]
# Function Call
result = solve(arr, queries)
for sum_val in result:
print(sum_val, end=" ")
print()
JavaScript
function GFG(arr, queries) {
// Creating a prefix Sum Array
let prefixSum = new Array(arr.length + 1).fill(0);
for (let i = 1; i <= arr.length; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
}
// Creating Result array to store the result of the each query
let result = [];
for (let query of queries) {
let l = query[0], r = query[1];
// Calculating sum for current query range
let sumVal = prefixSum[r] - prefixSum[l - 1];
result.push(sumVal);
}
return result;
}
// Sample Input
let arr = [3, 2, 4, 5, 1, 1, 5, 3];
let queries = [[2, 4], [5, 6], [1, 8], [3, 3]];
// Function Call
let result = GFG(arr, queries);
console.log(result.join(" "));
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)
Similar Reads
CSES Solutions - Path Queries You are given a rooted tree consisting of n nodes. The nodes are numbered 1,2,. . . .,n, and node 1 is the root. Each node has a value. Your task is to process following types of queries: change the value of node s to xcalculate the sum of values on the path from the root to node sExamples: Input: N
12 min read
Two equal sum segment range queries Given an array arr[] consisting of N positive integers, and some queries consisting of a range [L, R], the task is to find whether the sub-array from the given index range can be divided into two contiguous parts of non-zero length and equal sum.Examples: Input: arr[] = {1, 1, 2, 3}, q[] = {{0, 1},
9 min read
Subset Sum Queries in a Range using Bitset Given an array[] of N positive integers and M queries. Each query consists of two integers L and R represented by a range. For each query, find the count of numbers that lie in the given range which can be expressed as the sum of any subset of given array. Prerequisite : Subset Sum Queries using Bit
7 min read
CSES Solutions - Sum of Four Values You are given an array arr[] of N integers, and your task is to find four values (at distinct positions) whose sum is X. Note: If there are multiple answers, print any one of them.Examples:Input: N = 8, X = 15, arr[] = {3, 2, 5, 8, 1, 3, 2, 3}Output: 2 4 6 7Explanation: Elements at position 2, 4, 6
15+ min read
Sudo Placement | Range Queries Given Q queries, with each query consisting of two integers L and R, the task is to find the total numbers between L and R (Both inclusive), having almost three set bits in their binary representation. Examples: Input : Q = 2 L = 3, R = 7 L = 10, R = 16 Output : 5 6 For the first query, valid number
13 min read
Range sum queries without updates 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 = 4Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i
6 min read
Range Sum Queries and Update with Square Root Given an array A of N integers and number of queries Q. You have to answer two types of queries. Update [l, r] â for every i in range from l to r update Ai with sqrt(Ai), where sqrt(Ai) represents the square root of Ai in integral form.Query [l, r] â calculate the sum of all numbers ranging between
13 min read
CSES Solutions - Sum of Three Values You are given an array arr[] of N integers, and your task is to find three values (at distinct positions) whose sum is X. Note: The indices can be printed in any order. Examples: Input: N = 4, X = 8, arr[] = {2, 7, 5, 1}Output: 1 3 4Explanation: The elements at position 1, 3 and 4 are: 2, 5 and 1 re
9 min read
Range LCM Queries Given an array arr[] of integers of size N and an array of Q queries, query[], where each query is of type [L, R] denoting the range from index L to index R, the task is to find the LCM of all the numbers of the range for all the queries.Examples: Input: arr[] = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 4
15+ min read