Queries to calculate the Sum of Array elements in the range [L, R] having indices as multiple of K
Last Updated :
22 Feb, 2023
Given an array arr[] consisting of N integers, and a matrix Q[][] consisting of queries of the form (L, R, K), the task for each query is to calculate the sum of array elements from the range [L, R] which are present at indices(0- based indexing) which are multiples of K and
Examples:
Input: arr[]={1, 2, 3, 4, 5, 6}, Q[][]={{2, 5, 2}, {0, 5, 1}}
Output:
8
21
Explanation:
Query1: Indexes (2, 4) are multiple of K(= 2) from the range [2, 5]. Therefore, required Sum = 3+5 = 8.
Query2: Since all indices are a multiple of K(= 1), therefore, the required sum from the range [0, 5] = 1 + 2 + 3 + 4 + 5 + 6 = 21
Input: arr[]={4, 3, 5, 1, 9}, Q[][]={{1, 4, 1}, {3, 4, 3}}
Output:
18
1
Approach: The problem can be solved using Prefix Sum Array and Range sum query technique. Follow the steps below to solve the problem:
- Initialize a matrix of size prefixSum[][] such that prefixSum[i][j] stores the sum of elements present in indices which are a multiple of i up to jth index.
- Traverse the array and precompute the prefix sums.
- Traverse each query, and print the result of prefixSum[K][R] - prefixSum[K][L - 1].
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a Query
struct Node {
int L;
int R;
int K;
};
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
int kMultipleSum(int arr[], Node Query[],
int N, int Q)
{
// Stores Prefix Sum
int prefixSum[N + 1][N];
// prefixSum[i][j] : Stores the sum from
// indices [0, j] which are multiples of i
for (int i = 1; i <= N; i++) {
prefixSum[i][0] = arr[0];
for (int j = 0; j < N; j++) {
// If index j is a multiple of i
if (j % i == 0) {
// Compute prefix sum
prefixSum[i][j]
= arr[j] + prefixSum[i][j - 1];
}
// Otherwise
else {
prefixSum[i][j]
= prefixSum[i][j - 1];
}
}
}
// Traverse each query
for (int i = 0; i < Q; i++) {
// Sum of all indices upto R which
// are a multiple of K
int last
= prefixSum[Query[i].K][Query[i].R];
int first;
// Sum of all indices upto L - 1 which
// are a multiple of K
if (Query[i].L == 0) {
first
= prefixSum[Query[i].K][Query[i].L];
}
else {
first
= prefixSum[Query[i].K][Query[i].L - 1];
}
// Calculate the difference
cout << last - first << endl;
}
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
int Q = 2;
Node Query[Q];
Query[0].L = 2, Query[0].R = 5, Query[0].K = 2;
Query[1].L = 3, Query[1].R = 5, Query[1].K = 5;
kMultipleSum(arr, Query, N, Q);
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Structure of a Query
static class Node
{
int L;
int R;
int K;
};
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
static void kMultipleSum(int arr[], Node Query[],
int N, int Q)
{
// Stores Prefix Sum
int prefixSum[][] = new int[N + 1][N];
// prefixSum[i][j] : Stores the sum from
// indices [0, j] which are multiples of i
for(int i = 1; i <= N; i++)
{
prefixSum[i][0] = arr[0];
for(int j = 0; j < N; j++)
{
// If index j is a multiple of i
if (j % i == 0)
{
// Compute prefix sum
if (j != 0)
prefixSum[i][j] = arr[j] +
prefixSum[i][j - 1];
}
// Otherwise
else
{
prefixSum[i][j] = prefixSum[i][j - 1];
}
}
}
// Traverse each query
for(int i = 0; i < Q; i++)
{
// Sum of all indices upto R which
// are a multiple of K
int last = prefixSum[Query[i].K][Query[i].R];
int first;
// Sum of all indices upto L - 1 which
// are a multiple of K
if (Query[i].L == 0)
{
first = prefixSum[Query[i].K][Query[i].L];
}
else
{
first = prefixSum[Query[i].K][Query[i].L - 1];
}
// Calculate the difference
System.out.print(last - first + "\n");
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int N = arr.length;
int Q = 2;
Node Query[] = new Node[Q];
for(int i = 0; i < Q; i++)
Query[i] = new Node();
Query[0].L = 2;
Query[0].R = 5;
Query[0].K = 2;
Query[1].L = 3;
Query[1].R = 5;
Query[1].K = 5;
kMultipleSum(arr, Query, N, Q);
}
}
// This code is contributed by 29AjayKumar
Python3
class GFG :
# Structure of a Query
class Node :
L = 0
R = 0
K = 0
# Function to calculate the sum of array
# elements at indices from range [L, R]
# which are multiples of K for each query
@staticmethod
def kMultipleSum( arr, Query, N, Q) :
# Stores Prefix Sum
prefixSum = [[0] * (N) for _ in range(N + 1)]
# prefixSum[i][j] : Stores the sum from
# indices [0, j] which are multiples of i
i = 1
while (i <= N) :
prefixSum[i][0] = arr[0]
j = 0
while (j < N) :
# If index j is a multiple of i
if (j % i == 0) :
# Compute prefix sum
if (j != 0) :
prefixSum[i][j] = arr[j] + prefixSum[i][j - 1]
else :
prefixSum[i][j] = prefixSum[i][j - 1]
j += 1
i += 1
# Traverse each query
i = 0
while (i < Q) :
# Sum of all indices upto R which
# are a multiple of K
last = prefixSum[Query[i].K][Query[i].R]
first = 0
# Sum of all indices upto L - 1 which
# are a multiple of K
if (Query[i].L == 0) :
first = prefixSum[Query[i].K][Query[i].L]
else :
first = prefixSum[Query[i].K][Query[i].L - 1]
# Calculate the difference
print(str(last - first) + "\n", end ="")
i += 1
# Driver Code
@staticmethod
def main( args) :
arr = [1, 2, 3, 4, 5, 6]
N = len(arr)
Q = 2
Query = [None] * (Q)
i = 0
while (i < Q) :
Query[i] = GFG.Node()
i += 1
Query[0].L = 2
Query[0].R = 5
Query[0].K = 2
Query[1].L = 3
Query[1].R = 5
Query[1].K = 5
GFG.kMultipleSum(arr, Query, N, Q)
if __name__=="__main__":
GFG.main([])
# This code is contributed by aadityaburujwale.
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Structure of a Query
class Node
{
public int L;
public int R;
public int K;
};
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
static void kMultipleSum(int []arr, Node []Query,
int N, int Q)
{
// Stores Prefix Sum
int [,]prefixSum = new int[N + 1, N];
// prefixSum[i,j] : Stores the sum from
// indices [0, j] which are multiples of i
for(int i = 1; i <= N; i++)
{
prefixSum[i, 0] = arr[0];
for(int j = 0; j < N; j++)
{
// If index j is a multiple of i
if (j % i == 0)
{
// Compute prefix sum
if (j != 0)
prefixSum[i, j] = arr[j] +
prefixSum[i, j - 1];
}
// Otherwise
else
{
prefixSum[i, j] = prefixSum[i, j - 1];
}
}
}
// Traverse each query
for(int i = 0; i < Q; i++)
{
// Sum of all indices upto R which
// are a multiple of K
int last = prefixSum[Query[i].K,Query[i].R];
int first;
// Sum of all indices upto L - 1 which
// are a multiple of K
if (Query[i].L == 0)
{
first = prefixSum[Query[i].K,Query[i].L];
}
else
{
first = prefixSum[Query[i].K,Query[i].L - 1];
}
// Calculate the difference
Console.Write(last - first + "\n");
}
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4, 5, 6 };
int N = arr.Length;
int Q = 2;
Node []Query = new Node[Q];
for(int i = 0; i < Q; i++)
Query[i] = new Node();
Query[0].L = 2;
Query[0].R = 5;
Query[0].K = 2;
Query[1].L = 3;
Query[1].R = 5;
Query[1].K = 5;
kMultipleSum(arr, Query, N, Q);
}
}
// This code is contributed by 29AjayKumar
JavaScript
class Node {
constructor(L, R, K) {
this.L = L;
this.R = R;
this.K = K;
}
}
function kMultipleSum(arr, Query, N, Q)
{
// Stores Prefix Sum
let prefixSum = new Array(N + 1);
prefixSum[0] = new Array(N);
for (let i = 1; i <= N; i++)
{
prefixSum[i] = new Array(N);
prefixSum[i][0] = arr[0];
for (let j = 1; j < N; j++)
{
if (j % i === 0) {
prefixSum[i][j] = arr[j] + prefixSum[i][j - 1];
} else {
prefixSum[i][j] = prefixSum[i][j - 1];
}
}
}
// Traverse each query
for (let i = 0; i < Q; i++) {
last = prefixSum[Query[i].K][Query[i].R];
if (Query[i].L === 1) {
first = prefixSum[Query[i].K][0];
} else {
first = prefixSum[Query[i].K][Query[i].L -1];
}
console.log(last - first);
}
}
let arr = [ 1, 2, 3, 4, 5, 6 ];
let N = arr.length;
let Q = 2;
let Query=[];
Query.push(new Node(2,5,2));
Query.push(new Node(3,5,5));
//Query[0].L = 2, Query[0].R = 5, Query[0].K = 2;
//Query[1].L = 3, Query[1].R = 5, Query[1].K = 5;
kMultipleSum(arr, Query, N, Q);
// This code is contributed by poojaagarwal2.
Time Complexity: O(N2 + O(Q)), Computing the prefix sum array requires O(N2) computational complexity and each query requires O(1) computational complexity.
Auxiliary Space: O(N2)
Method 2:-
- Just traverse all the queries.
- For all the queries traverse the array from L or R.
- Check if the index is divisible by K or not. If yes then and the element into answer.
- In the end of each query print the answer
Solution for the above Approach:-
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a Query
struct Node {
int L;
int R;
int K;
};
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
void kMultipleSum(int arr[], Node Query[],
int N, int Q)
{
//Traversing All Queries
for(int j=0;j<Q;j++){
//Taking L into Start
int start = Query[j].L;
//Taking R into End
int end = Query[j].R;
int answer=0;
for(int i=start;i<=end;i++)
{
if(i%Query[j].K==0)answer+=arr[i];
}
//Printing Answer for Each Query
cout<<answer<<endl;
}
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
int Q = 2;
Node Query[Q];
Query[0].L = 2, Query[0].R = 5, Query[0].K = 2;
Query[1].L = 3, Query[1].R = 5, Query[1].K = 5;
kMultipleSum(arr, Query, N, Q);
}
Java
// Java Program to implement the above approach
import java.io.*;
// Structure of a Query
class Node {
int L, R, K;
Node(int L, int R, int K)
{
this.L = L;
this.R = R;
this.K = K;
}
}
class GFG {
// Function to calculate the sum of array elements at
// indices from range [L, R] which are multiples of K
// for each query
static void kMultipleSum(int[] arr, Node[] Query, int N,
int Q)
{
// Traversing All Queries
for (int j = 0; j < Q; j++) {
// Taking L into Start
int start = Query[j].L;
// Taking R into End
int end = Query[j].R;
int answer = 0;
for (int i = start; i <= end; i++) {
if (i % Query[j].K == 0)
answer += arr[i];
}
// Printing Answer for Each Query
System.out.println(answer);
}
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6 };
int N = arr.length;
int Q = 2;
Node[] Query = new Node[Q];
Query[0] = new Node(2, 5, 2);
Query[1] = new Node(3, 5, 5);
kMultipleSum(arr, Query, N, Q);
}
}
// This code is contributed by sankar.
Python3
# Python Program to implement the above approach
# Structure of a Query
class Node:
def __init__(self, L, R, K):
self.L = L
self.R = R
self.K = K
# Function to calculate the sum of array
# elements at indices from range [L, R]
# which are multiples of K for each query
def kMultipleSum(arr, Query, N, Q):
# Traversing All Queries
for j in range(Q):
# Taking L into Start
start = Query[j].L
# Taking R into End
end = Query[j].R
answer = 0
for i in range(start, end + 1):
if i % Query[j].K == 0:
answer += arr[i]
# Printing Answer for Each Query
print(answer)
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6]
N = len(arr)
Q = 2
Query = [Node(2, 5, 2), Node(3, 5, 5)]
kMultipleSum(arr, Query, N, Q)
C#
// C# Program to implement
// the above approach
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Structure of a Query
class Node {
public int L, R, K;
public Node(int L, int R, int K)
{
this.L=L;
this.R=R;
this.K=K;
}
}
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
static void kMultipleSum(int[] arr, Node[] Query,
int N, int Q)
{
//Traversing All Queries
for(int j=0;j<Q;j++){
//Taking L into Start
int start = Query[j].L;
//Taking R into End
int end = Query[j].R;
int answer=0;
for(int i=start;i<=end;i++)
{
if(i%Query[j].K==0)
answer+=arr[i];
}
//Printing Answer for Each Query
Console.WriteLine(answer);
}
}
// Driver Code
static public void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6 };
int N = arr.Length;
int Q = 2;
Node[] Query=new Node[Q];
Query[0]=new Node(2,5,2);
Query[1]=new Node(3,5,5);
kMultipleSum(arr, Query, N, Q);
}
}
JavaScript
// Javascript Program to implement
// the above approach
// Structure of a Query
class Node {
constructor(L,R,K)
{
this.L=L;
this.R=R;
this.K=K;
}
}
// Function to calculate the sum of array
// elements at indices from range [L, R]
// which are multiples of K for each query
function kMultipleSum(arr, Query, N, Q)
{
//Traversing All Queries
for(let j=0;j<Q;j++){
//Taking L into Start
let start = Query[j].L;
//Taking R into End
let end = Query[j].R;
let answer=0;
for(let i=start;i<=end;i++)
{
if(i%Query[j].K==0)
answer+=arr[i];
}
//Printing Answer for Each Query
console.log(answer);
}
}
// Driver Code
let arr = [ 1, 2, 3, 4, 5, 6 ];
let N = arr.length;
let Q = 2;
let Query=[];
Query.push(new Node(2,5,2));
Query.push(new Node(3,5,5));
/*Query[0].L = 2, Query[0].R = 5, Query[0].K = 2;
Query[1].L = 3, Query[1].R = 5, Query[1].K = 5;*/
kMultipleSum(arr, Query, N, Q);
Time Complexity:- O(Q*N)
Auxiliary Space:- O(1)
Similar Reads
Queries to calculate sum of squares of array elements over range of indices [L, R] with updates Given an Array arr[] of positive integers of size n. We are required to perform following 3 queries on given array - 1) Given L and R, we have to find the sum of squares of all element lying in range [L,R] 2) Given L, R and X, we have to set all element lying in range [L,R] to X 3) Given L, R and X,
15+ min read
Maximum element present in the array after performing queries to add K to range of indices [L, R] Given an array arr[] consisting of N integers, ( initially set to 0 ) and an array Q[], consisting of queries of the form {l, r, k}, the task for each query is to add K to the indices l to r(both inclusive). After performing all queries, return the maximum element present the array. Example: Input:
7 min read
Sum of multiples of Array elements within a given range [L, R] Given an array arr[] of positive integers and two integers L and R, the task is to find the sum of all multiples of the array elements in the range [L, R]. Examples: Input: arr[] = {2, 7, 3, 8}, L = 7, R = 20 Output: 197 Explanation: In the range 7 to 20: Sum of multiples of 2: 8 + 10 + 12 + 14 + 16
7 min read
Find the summation of the product of Array elements in range [L, R] Given an array arr[] and two integers L and R. The task is to find the sum of the product of all the pairs (i, j) in the range [L, R], such that i ⤠j. Input: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2Output: 58Explanation: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58 Input: arr[] = { 2, 1, 4, 5, 3, 2, 1 },
8 min read
Count of Array elements in given range with remainder X when divided by K for Q queries Given an array arr[] of size N, an integer K and Q queries, each of form {x, l, r}. For each query, the task is to find the count of all elements in index range [l, r] which have remainder x when divided by K. Examples: Input: arr[] = {15, 28, 72, 43, 20, 0, 97}, K = 5, queries[] = {{3, 0, 3}, {0, 0
14 min read
Find the index of the smallest element to be removed to make sum of array divisible by K Given an array arr[] of size N and a positive integer K, the task is to find the index of the smallest array element required to be removed to make the sum of remaining array divisible by K. If multiple solutions exist, then print the smallest index. Otherwise, print -1. Examples: Input: arr[ ] = {6
8 min read
Count of elements which is the sum of a subarray of the given Array Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
7 min read
Perform K of Q queries to maximize the sum of the array elements Given an array arr[] of N integers and an integer K. Also given are Q queries which have two numbers L and R. For every query, you can increase all the elements of the array in the index range [L, R] by 1. The task is to choose exactly K queries out of Q queries such that the sum of the array at the
7 min read
Count of elements in an Array whose set bits are in a multiple of K Given an array arr[] of N elements and an integer K, the task is to count all the elements whose number of set bits is a multiple of K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 2 Explanation: Two numbers whose setbits count is multiple of 2 are {3, 5}.Input: arr[] = {10, 20, 30, 40}, K
9 min read
Count set bits in index range [L, R] in given Array for Q queries Given an array arr[] containing N integers and an array queries[] containing Q queries in the form of {L, R}, the task is to count the total number of set bits from L to R in array arr for each query. Example: Input: arr[]={1, 2, 3, 4, 5, 6}, queries[]={{0, 2}, {1, 1}, {3, 5}}Output:425Explanation:Q
6 min read