Find Array obtained after adding terms of AP for Q queries
Last Updated :
08 Mar, 2023
Given an array A[] consisting of N integers and Q queries, say Query[][] of the form {L, R, a, d} such that each query represents the infinite AP with the first term as a and common difference d. The task is to print the updated array after performing the given queries such that for each query {L, R, a, d} add the value of (i - L + 1)th term of the arithmetic progression to A[i] for every index i over the range [L, R].
Examples:
Input: A[]= {5, 4, 2, 8}, Q = 2, Query[][] = {{1, 2, 1, 3}, {1, 4, 4, 1}}
Output: 10 13 8 15
Explanation:
Following are the queries performed:
Query 1: The arithmetic progression is {1, 4, 7, ...}. After adding the first term of the progression to index 1 and the second term of the progression to index 2, the array modifies to {6, 8, 2, 8}.
Query 2: The arithmetic progression is {4, 5, 6, 7, 8, ...}. After adding 4 to A[1], 5 to A[2], 6 to A[3] and 7 to A[4] the array modifies to {10, 13, 8 15}.
Therefore, the resultant array is {10, 13, 8 15}.
Input: A[] = {1, 2, 3, 4, 5}, Q = 3, Query[][] = {{1, 2, 1, 3}, {1, 3, 4, 1}, {1, 4, 1, 2}}
Output: 7 14 14 11 5
Approach: The given problem can be solved by iterating over the range [L, R] in each operation and add the corresponding term of the given arithmetic progression at each index i. Follow the steps below to solve the problem:
- Traverse the array, Query[][] using the variable i and for each query {L, R, a, d} perform the following steps:
- Traverse the array A[], in the range [L - 1, R - 1] using the variable j
- Add the value of a to the value of A[j].
- Increment the value of a by d.
- After completing the above steps, print the array A[] as the resultant updated array.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
// Function to find array after performing
// the given query to the array elements
void addAP(int A[], int Q, int operations[2][4])
{
// Traverse the given query
for (int j = 0; j < 2; ++j)
{
int L = operations[j][0], R = operations[j][1], a = operations[j][2], d = operations[j][3];
int curr = a;
// Traverse the given array
for(int i = L - 1; i < R; i++){
// Update the value of A[i]
A[i] += curr;
// Update the value of curr
curr += d;
}
}
// Print the array elements
for (int i = 0; i < 4; ++i)
cout << A[i] << " ";
}
// Driver Code
int main() {
int A[] = {5, 4, 2, 8};
int Q = 2;
int Query[2][4] = {{1, 2, 1, 3}, {1, 4, 4, 1}};
// Function Call
addAP(A, Q, Query);
return 0;
}
// This code is contributed by shubhamsingh10.
C
// C program for the above approach
#include <stdio.h>
// Function to find array after performing
// the given query to the array elements
void addAP(int A[], int Q, int operations[2][4])
{
// Traverse the given query
for (int j = 0; j < 2; ++j)
{
int L = operations[j][0], R = operations[j][1], a = operations[j][2], d = operations[j][3];
int curr = a;
// Traverse the given array
for(int i = L - 1; i < R; i++){
// Update the value of A[i]
A[i] += curr;
// Update the value of curr
curr += d;
}
}
// Print the array elements
for (int i = 0; i < 4; ++i)
printf("%d ", A[i]);
}
// Driver Code
int main() {
int A[] = {5, 4, 2, 8};
int Q = 2;
int Query[2][4] = {{1, 2, 1, 3}, {1, 4, 4, 1}};
// Function Call
addAP(A, Q, Query);
return 0;
}
// This code is contributed by shubhamsingh10.
Java
// Java program for the above approach
class GFG {
// Function to find array after performing
// the given query to the array elements
public static void addAP(int A[], int Q, int[][] operations)
{
// Traverse the given query
for (int j = 0; j < 2; ++j) {
int L = operations[j][0], R = operations[j][1],
a = operations[j][2], d = operations[j][3];
int curr = a;
// Traverse the given array
for (int i = L - 1; i < R; i++) {
// Update the value of A[i]
A[i] += curr;
// Update the value of curr
curr += d;
}
}
// Print the array elements
for (int i = 0; i < 4; ++i)
System.out.print(A[i] + " ");
}
// Driver Code
public static void main(String args[])
{
int A[] = { 5, 4, 2, 8 };
int Q = 2;
int query[][] = { { 1, 2, 1, 3 }, { 1, 4, 4, 1 } };
// Function Call
addAP(A, Q, query);
}
}
// This code is contributed by _saurabh_jaiswal
Python3
# Python program for the above approach
# Function to find array after performing
# the given query to the array elements
def addAP(A, Q, operations):
# Traverse the given query
for L, R, a, d in operations:
curr = a
# Traverse the given array
for i in range(L-1, R):
# Update the value of A[i]
A[i] += curr
# Update the value of curr
curr += d
# Print the array elements
for i in A:
print(i, end =' ')
# Driver Code
A = [5, 4, 2, 8]
Q = 2
Query = [(1, 2, 1, 3), (1, 4, 4, 1)]
# Function Call
addAP(A, Q, Query)
C#
// C# program for the above approach
using System;
class GFG{
// Function to find array after performing
// the given query to the array elements
public static void addAP(int[] A, int Q,
int[,] operations)
{
// Traverse the given query
for(int j = 0; j < 2; ++j)
{
int L = operations[j, 0], R = operations[j, 1],
a = operations[j, 2], d = operations[j, 3];
int curr = a;
// Traverse the given array
for(int i = L - 1; i < R; i++)
{
// Update the value of A[i]
A[i] += curr;
// Update the value of curr
curr += d;
}
}
// Print the array elements
for(int i = 0; i < 4; ++i)
Console.Write(A[i] + " ");
}
// Driver code
public static void Main(string[] args)
{
int[] A = { 5, 4, 2, 8 };
int Q = 2;
int[,] query = { { 1, 2, 1, 3 },
{ 1, 4, 4, 1 } };
// Function Call
addAP(A, Q, query);
}
}
// This code is contributed by avijitmondal1998
JavaScript
<script>
// Javascript program for the above approach
// Function to find array after performing
// the given query to the array elements
function addAP(A, Q, operations)
{
// Traverse the given query
for( let Q of operations)
{
let L = Q[0], R = Q[1], a = Q[2], d = Q[3]
curr = a
// Traverse the given array
for(let i = L - 1; i < R; i++){
// Update the value of A[i]
A[i] += curr
// Update the value of curr
curr += d
}
}
// Print the array elements
for (let i of A){
document.write(i + " ")
}
}
// Driver Code
let A = [5, 4, 2, 8]
let Q = 2
let Query = [[1, 2, 1, 3], [1, 4, 4, 1]]
// Function Call
addAP(A, Q, Query)
// This code is contributed by gfgking.
</script>
Time Complexity: O(N*Q)
Auxiliary Space: O(1)
Efficient Approach: Let us declare 2 variables X which represents all the differences running that is ( d1 + d2 + d3 ... ), and S which is the cumulative Sum that represents the resultant sum of all applied AP at index {i-1}.
So the cumulative sum of the new index {i} will be:
1. X[i] =X[i-1] + X' { correction of difference i.e. starting or ending of AP}
2. S[i] = S[i-1] + S' { correction of Cumulative sum i.e. starting or ending of AP}
3. S[i] = S[i] + X[i]
4. Arr[i] = Arr[i] + S[i]
Below is the implementation of the above approach:
C++14
// Code by Omkar Tripathi
#include<bits/stdc++.h>
const char nl = '\n';
using namespace std;
void mysolution(vector<int> &arr, vector<vector<int>> &query){
int n = arr.size();
// array used to simulate extra addition (d1 + d2 + d3 + d4...) we perform with every increment
vector<int> collective_D(n+1, 0);
/*
When we reach the end of AP we make correction of the extire sum of AP
for the element that sum is useless but because it is part of
S( variable we are using to take collective sum) so we make correction for the new index.
*/
vector<int> S_collective_correction(n+1,0);
int l, r, d, a, X=0, S=0;
/* Here X variable used keeps track of d1 + d2 + d3 ... numbers of parrarel AP we are using because if we look
carefully next element difference with current element is X ( d1 + d2 + d3 ... numbers of parrarel AP) */
/* The other part of sum is captured by S and we make collective correction at the end of AP */
for(auto q: query){
l = q[0]; r = q[1]; a = q[2]; d = q[3];
r--;
collective_D[l] += d;
collective_D[r+1] -= d;
S_collective_correction[l-1] += (a);
S_collective_correction[r+1] -= a + (r+1-l)*d;
}
for(int i = 0; i < n; i++){
X += collective_D[i]; // X denotes the current D ( d1 + d2 + d3.. ) that are running in parallel.
S += S_collective_correction[i]; // If some AP starts or ends this makes necessary correction.
S += X; // S is the ( a1 + a2+ a3) + (n1*d1 + n2*d2 + n3*d3)
arr[i] += (S);
}
for(int i: arr) cout<<i<<' ';
cout<<nl;
}
void solve(){
vector<int> v = {5,4,2,8};
// query format {l r, a, d}
vector<vector<int>> query = {{1,2,1,3},{1,4,4,1}};
mysolution(v, query);
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T = 1;
while(T--){
solve();
}
return 0;
}
// Code contributed by Omkar Tripathi
Java
import java.util.*;
class Main {
static void mysolution(int[] arr, int[][] query) {
int n = arr.length;
// array used to simulate extra addition
// (d1 + d2 + d3 + d4...) we perform with every increment
int[] collective_D = new int[n+1];
/*
When we reach the end of AP
we make correction of the extire sum of AP
for the element that sum is useless
but because it is part of
S( variable we are using to take collective sum)
so we make correction for the new index.
*/
int[] S_collective_correction = new int[n+1];
int l, r, d, a, X=0, S=0;
/* Here X variable used keeps track of d1 + d2 + d3 ...
numbers of parrarel AP we are using because if we look
carefully next element difference with
current element is X ( d1 + d2 + d3 ... numbers of parrarel AP) */
/* The other part of sum is captured by S and
we make collective correction at the end of AP */
for(int[] q: query){
l = q[0]; r = q[1]; a = q[2]; d = q[3];
r--;
collective_D[l] += d;
collective_D[r+1] -= d;
S_collective_correction[l-1] += (a);
S_collective_correction[r+1] -= a + (r+1-l)*d;
}
for(int i = 0; i < n; i++){
X += collective_D[i]; // X denotes the current D ( d1 + d2 + d3.. ) that are running in parallel.
S += S_collective_correction[i]; // If some AP starts or ends this makes necessary correction.
S += X; // S is the ( a1 + a2+ a3) + (n1*d1 + n2*d2 + n3*d3)
arr[i] += (S);
}
for(int i: arr) System.out.print(i + " ");
System.out.println();
}
public static void main(String[] args) {
int[] v = {5,4,2,8};
// query format {l r, a, d}
int[][] query = {{1,2,1,3},{1,4,4,1}};
mysolution(v, query);
}
}
Python3
def mysolution(arr, query):
n = len(arr)
# array used to simulate extra addition
# (d1 + d2 + d3 + d4...) we perform with every increment
collective_D = [0] * (n+1)
"""
When we reach the end of AP
we make correction of the entire sum of AP
for the element that sum is useless
but because it is part of
S (variable we are using to take collective sum)
so we make correction for the new index.
"""
S_collective_correction = [0] * (n+1)
X, S = 0, 0
"""
Here X variable used keeps track of d1 + d2 + d3 ...
numbers of parallel AP we are using because if we look
carefully next element difference with
current element is X ( d1 + d2 + d3 ... numbers of parallel AP)
The other part of sum is captured by S and
we make collective correction at the end of AP.
"""
for q in query:
l, r, a, d = q
r -= 1
collective_D[l] += d
collective_D[r+1] -= d
S_collective_correction[l-1] += a
S_collective_correction[r+1] -= a + (r+1-l)*d
for i in range(n):
X += collective_D[i] # X denotes the current D ( d1 + d2 + d3.. ) that are running in parallel.
S += S_collective_correction[i] # If some AP starts or ends this makes necessary correction.
S += X # S is the ( a1 + a2+ a3) + (n1*d1 + n2*d2 + n3*d3)
arr[i] += S
print(*arr)
v = [5,4,2,8]
# query format [l, r, a, d]
query = [[1,2,1,3],[1,4,4,1]]
mysolution(v, query)
JavaScript
function mysolution(arr, query) {
const n = arr.length;
const collective_D = new Array(n+1).fill(0);
const S_collective_correction = new Array(n+1).fill(0);
let l, r, d, a, X=0, S=0;
for (const q of query) {
[l, r, a, d] = q;
r--;
collective_D[l] += d;
collective_D[r+1] -= d;
S_collective_correction[l-1] += a;
S_collective_correction[r+1] -= a + (r+1-l)*d;
}
for (let i = 0; i < n; i++) {
X += collective_D[i];
S += S_collective_correction[i];
S += X;
arr[i] += S;
}
console.log(arr.join(' '));
}
const v = [5, 4, 2, 8];
const query = [[1, 2, 1, 3], [1, 4, 4, 1]];
mysolution(v, query);
C#
using System;
class MainClass {
static void Mysolution(int[] arr, int[][] query)
{
int n = arr.Length;
// array used to simulate extra addition
// (d1 + d2 + d3 + d4...) we perform with every
// increment
int[] collective_D = new int[n + 1];
/*
When we reach the end of AP
we make correction of the extire sum of AP
for the element that sum is useless
but because it is part of
S (variable we are using to take collective sum)
so we make correction for the new index.
*/
int[] S_collective_correction = new int[n + 1];
int l, r, d, a, X = 0, S = 0;
/* Here X variable used keeps track of d1 + d2 + d3
... numbers of parrarel AP we are using because if
we look carefully next element difference with
current element is X (d1 + d2 + d3 ... numbers of
parrarel AP) */
/* The other part of sum is captured by S and
we make collective correction at the end of AP */
foreach(int[] q in query)
{
l = q[0];
r = q[1];
a = q[2];
d = q[3];
r--;
collective_D[l] += d;
collective_D[r + 1] -= d;
S_collective_correction[l - 1] += a;
S_collective_correction[r + 1]
-= a + (r + 1 - l) * d;
}
for (int i = 0; i < n; i++) {
X += collective_D
[i]; // X denotes the current D (d1 + d2 +
// d3..) that are running in parallel.
S += S_collective_correction
[i]; // If some AP starts or ends this makes
// necessary correction.
S += X; // S is the (a1 + a2 + a3) + (n1*d1 +
// n2*d2 + n3*d3)
arr[i] += S;
}
foreach(int i in arr) Console.Write(i + " ");
Console.WriteLine();
}
public static void Main()
{
int[] v = { 5, 4, 2, 8 };
// query format {l r, a, d}
int[][] query
= new int[][] { new int[] { 1, 2, 1, 3 },
new int[] { 1, 4, 4, 1 } };
Mysolution(v, query);
}
}
Time Complexity : max(O(q) , O(N))
Space Complexity: O(N)
Similar Reads
Find the Array formed by performing Q queries on an empty array Consider an integer sequence S, which is initially empty (i.e. S = {}). Also given are Q queries, each of which is one of the following types: 1 a b: Insert a and b into the sequence S.2 a b: In the sequence S, among the elements that are less than or equal to a, print b-th largest element. If no su
14 min read
Array sum after replacing all occurrences of X by Y for Q queries Given an integer array arr[] and Q queries, the task is to find the sum of the array for each query of the following type: Each query contains 2 integers X and Y, where all the occurrences of X in arr[] are to be replaced by Y.After each query, they print the sum of the array. Examples: Input: arr[]
8 min read
Sum of P terms of an AP if Mth and Nth terms are given Given Mth and Nth terms of arithmetic progression. The task is to find the sum of its first p terms.Examples: Input: m = 6, n = 10, mth = 12, nth = 20, p = 5 Output:30Input:m = 10, n = 20, mth = 70, nth = 140, p = 4 Output:70 Approach: Let a is the first term and d is the common difference of the gi
7 min read
Find Array after Q queries where in each query change a[i] to a[i] | x Given an array of N elements, initially all a[i] = 0. Q queries need to be performed. Each query contains three integers l, r, and x and you need to change all a[i] to (a[i] | x) for all l ⤠i ⤠r and return the array after executing Q queries. Examples: Input: N = 3, Q = 2, U = {{1, 3, 1}, {1, 3, 2
12 min read
Find the sum of array after performing every query Given an array arr[] of size N and Q queries where every query contains two integers X and Y, the task is to find the sum of an array after performing each Q queries such that for every query, the element in the array arr[] with value X is updated to Y. Find the sum of the array after every query. E
7 min read