Queries to increment array elements in a given range by a given value for a given number of times
Last Updated :
10 Jun, 2022
Given an array, arr[] of N positive integers and M queries of the form {a, b, val, f}. The task is to print the array after performing each query to increment array elements in the range [a, b] by a value val f number of times.
Examples:
Input: arr[] = {1, 2, 3}, M=3, Q[][] = {{1, 2, 1, 4}, {1, 3, 2, 3}, {2, 3, 4, 5}}
Output: 11 32 29
Explanation:
After applying 1st Query 4 times,
Array will be: 5 6 3
After applying 2nd Query 3 times,
Array will be: 11 12 9
After applying 3rd Query 5 times,
Array will be: 11 32 29
Therefore, the final array will be {11, 32, 29}.
Input: arr[] = {1}, M = 1, Q[][] = {{1, 1, 1, 1}}
Output: 2
Explanation:
After applying 1st and the only query 1 time only.
Array will be: 2
Naive Approach: The simplest approach is to perform each query on the given array i.e., for each query {a, b, val, f} traverse the array over the range [a, b] and increase each element by value val to f number of times. Print the array after performing each query.
Time Complexity: O(N * M * max(Freq))
Auxiliary Space: O(1)
Better Approach: The idea is based on the difference array which can be used in Range Update operations. Below are the steps:
- Find the difference array D[] of a given array A[] is defined as D[i] = (A[i] - A[i - 1]) (0 < i < N) and D[0] = A[0] considering 0 based indexing.
- Add val to D[a - 1] and subtract it from D[(b - 1) + 1], i.e., D[a - 1] += val, D[(b - 1) + 1] -= val. Perform this operation Freq number of times.
- Now update the given array using the difference array. Update A[0] to D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i].
- Print the resultant array after the above steps.
Time Complexity: O(N + M * max(Freq))
Auxiliary Space: O(N) Extra space for Difference Array
Efficient Approach: This approach is similar to the previous approach but an extended version of the application of a difference array. Previously the task was to update values from indices a to b by val, f number of times. Here instead of calling the range update function f number of times, call it only once for each query:
- Update values from indices a to b by val*f, only 1 time for each query.
- Add val*f to D[a - 1] and subtract it from D[(b - 1) + 1], i.e., increase D[a - 1] by val*f, and decrease D[b] by val*f.
- Now update the main array using the difference array. Update A[0] to D[0] and print it.
- For rest of the elements, Update A[i] by (A[i-1] + D[i]).
- Print the resultant array after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function that creates a difference
// array D[] for A[]
vector<int> initializeDiffArray(
vector<int>& A)
{
int N = A.size();
// Stores the difference array
vector<int> D(N + 1);
D[0] = A[0], D[N] = 0;
// Update difference array D[]
for (int i = 1; i < N; i++)
D[i] = A[i] - A[i - 1];
// Return difference array
return D;
}
// Function that performs the range
// update queries
void update(vector<int>& D, int l,
int r, int x)
{
// Update the ends of the range
D[l] += x;
D[r + 1] -= x;
}
// Function that perform all query
// once with modified update Call
void UpdateDiffArray(vector<int>& DiffArray,
int Start, int End,
int Val, int Freq)
{
// For range update, difference
// array is modified
update(DiffArray, Start - 1,
End - 1, Val * Freq);
}
// Function to take queries
void queriesInput(vector<int>& DiffArray,
int Q[][4], int M)
{
// Traverse the query
for (int i = 0; i < M; i++) {
// Function Call for updates
UpdateDiffArray(DiffArray, Q[i][0],
Q[i][1], Q[i][2],
Q[i][3]);
}
}
// Function to updates the array
// using the difference array
void UpdateArray(vector<int>& A,
vector<int>& D)
{
// Traverse the array A[]
for (int i = 0; i < A.size(); i++) {
// 1st Element
if (i == 0) {
A[i] = D[i];
}
// A[0] or D[0] decides values
// of rest of the elements
else {
A[i] = D[i] + A[i - 1];
}
}
}
// Function that prints the array
void PrintArray(vector<int>& A)
{
// Print the element
for (int i = 0; i < A.size(); i++) {
cout << A[i] << " ";
}
return;
}
// Function that print the array
// after performing all queries
void printAfterUpdate(vector<int>& A,
int Q[][4], int M)
{
// Create and fill difference
// array for range updates
vector<int> DiffArray
= initializeDiffArray(A);
queriesInput(DiffArray, Q, M);
// Now update Array A using
// Difference Array
UpdateArray(A, DiffArray);
// Print updated Array A
// after M queries
PrintArray(A);
}
// Driver Code
int main()
{
// N = Array size, M = Queries
int N = 3, M = 3;
// Given array A[]
vector<int> A{ 1, 2, 3 };
// Queries
int Q[][4] = { { 1, 2, 1, 4 },
{ 1, 3, 2, 3 },
{ 2, 3, 4, 5 } };
// Function Call
printAfterUpdate(A, Q, M);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
// N = Array size,
// M = Queries
static int N = 3, M = 3;
static int []A = new int[N];
//Stores the difference array
static int []D = new int[N + 1];
// Function that creates
// a difference array D[]
// for A[]
static void initializeDiffArray()
{
D[0] = A[0];
D[N] = 0;
// Update difference array D[]
for (int i = 1; i < N; i++)
D[i] = A[i] - A[i - 1];
}
// Function that performs
// the range update queries
static void update(int l,
int r, int x)
{
// Update the ends
// of the range
D[l] += x;
D[r + 1] -= x;
}
// Function that perform all query
// once with modified update Call
static void UpdateDiffArray(int Start, int End,
int Val, int Freq)
{
// For range update, difference
// array is modified
update(Start - 1,
End - 1, Val * Freq);
}
// Function to take queries
static void queriesInput( int Q[][])
{
// Traverse the query
for (int i = 0; i < M; i++)
{
// Function Call for updates
UpdateDiffArray(Q[i][0], Q[i][1],
Q[i][2], Q[i][3]);
}
}
// Function to updates the array
// using the difference array
static void UpdateArray()
{
// Traverse the array A[]
for (int i = 0; i < N; i++)
{
// 1st Element
if (i == 0)
{
A[i] = D[i];
}
// A[0] or D[0] decides
// values of rest of
// the elements
else
{
A[i] = D[i] + A[i - 1];
}
}
}
// Function that prints
// the array
static void PrintArray()
{
// Print the element
for (int i = 0; i < N; i++)
{
System.out.print(A[i] + i +
1 + " ");
}
return;
}
// Function that print the array
// after performing all queries
static void printAfterUpdate(int []A,
int Q[][], int M)
{
// Create and fill difference
// array for range updates
initializeDiffArray();
queriesInput( Q);
// Now update Array
// A using Difference
// Array
UpdateArray();
// Print updated Array A
// after M queries
PrintArray();
}
// Driver Code
public static void main(String[] args)
{
// Given array A[]
int []A = {1, 2, 3};
// Queries
int [][]Q = {{1, 2, 1, 4},
{1, 3, 2, 3},
{2, 3, 4, 5}};
// Function Call
printAfterUpdate(A, Q, M);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
# Function that creates a difference
# array D[] for A[]
def initializeDiffArray(A):
N = len(A)
# Stores the difference array
D = [0] * (N + 1)
D[0] = A[0]
D[N] = 0
# Update difference array D[]
for i in range(1, N):
D[i] = A[i] - A[i - 1]
# Return difference array
return D
# Function that performs the range
# update queries
def update(D, l, r, x):
# Update the ends of the range
D[l] += x
D[r + 1] -= x
# Function that perform all query
# once with modified update Call
def UpdateDiffArray(DiffArray, Start,
End, Val, Freq):
# For range update, difference
# array is modified
update(DiffArray, Start - 1,
End - 1, Val * Freq)
# Function to take queries
def queriesInput(DiffArray, Q, M):
# Traverse the query
for i in range(M):
# Function Call for updates
UpdateDiffArray(DiffArray, Q[i][0],
Q[i][1], Q[i][2],
Q[i][3])
# Function to updates the array
# using the difference array
def UpdateArray(A, D):
# Traverse the array A[]
for i in range(len(A)):
# 1st Element
if (i == 0):
A[i] = D[i]
# A[0] or D[0] decides values
# of rest of the elements
else:
A[i] = D[i] + A[i - 1]
# Function that prints the array
def PrintArray(A):
# Print the element
for i in range(len(A)):
print(A[i], end = " ")
return
# Function that print the array
# after performing all queries
def printAfterUpdate(A, Q, M):
# Create and fill difference
# array for range updates
DiffArray = initializeDiffArray(A)
queriesInput(DiffArray, Q, M)
# Now update Array A using
# Difference Array
UpdateArray(A, DiffArray)
# Print updated Array A
# after M queries
PrintArray(A)
# Driver Code
if __name__ == '__main__':
# N = Array size, M = Queries
N = 3
M = 3
# Given array A[]
A = [ 1, 2, 3 ]
# Queries
Q = [ [ 1, 2, 1, 4 ],
[ 1, 3, 2, 3 ],
[ 2, 3, 4, 5 ] ]
# Function call
printAfterUpdate(A, Q, M)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
class GFG{
// N = Array size,
// M = Queries
static int N = 3, M = 3;
static int[] A = new int[N];
// Stores the difference array
static int[] D = new int[N + 1];
// Function that creates
// a difference array D[]
// for A[]
static void initializeDiffArray()
{
D[0] = A[0];
D[N] = 0;
// Update difference array D[]
for (int i = 1; i < N; i++)
D[i] = A[i] - A[i - 1];
}
// Function that performs
// the range update queries
static void update(int l,
int r, int x)
{
// Update the ends
// of the range
D[l] += x;
D[r + 1] -= x;
}
// Function that perform all query
// once with modified update Call
static void UpdateDiffArray(int Start, int End,
int Val, int Freq)
{
// For range update, difference
// array is modified
update(Start - 1,
End - 1, Val * Freq);
}
// Function to take queries
static void queriesInput(int[, ] Q)
{
// Traverse the query
for (int i = 0; i < M; i++)
{
// Function Call for updates
UpdateDiffArray(Q[i, 0], Q[i, 1],
Q[i, 2], Q[i, 3]);
}
}
// Function to updates the array
// using the difference array
static void UpdateArray()
{
// Traverse the array A[]
for (int i = 0; i < N; i++)
{
// 1st Element
if (i == 0)
{
A[i] = D[i];
}
// A[0] or D[0] decides
// values of rest of
// the elements
else
{
A[i] = D[i] + A[i - 1];
}
}
}
// Function that prints
// the array
static void PrintArray()
{
// Print the element
for (int i = 0; i < N; i++)
{
Console.Write(A[i] + i +
1 + " ");
}
return;
}
// Function that print the array
// after performing all queries
static void printAfterUpdate(int[] A,
int[, ] Q, int M)
{
// Create and fill difference
// array for range updates
initializeDiffArray();
queriesInput(Q);
// Now update Array
// A using Difference
// Array
UpdateArray();
// Print updated Array A
// after M queries
PrintArray();
}
// Driver Code
public static void Main(String[] args)
{
// Given array A[]
int[] A = {1, 2, 3};
// Queries
int[, ] Q = {{1, 2, 1, 4},
{1, 3, 2, 3},
{2, 3, 4, 5}};
// Function Call
printAfterUpdate(A, Q, M);
}
// This code is contributed by Chitranayal
JavaScript
<script>
// Javascript program to implement
// the above approach
// N = Array size,
// M = Queries
let N = 3, M = 3;
let A = new Array(N).fill(0);
//Stores the difference array
let D = new Array(N+1).fill(0);
// Function that creates
// a difference array D[]
// for A[]
function initializeDiffArray()
{
D[0] = A[0];
D[N] = 0;
// Update difference array D[]
for (let i = 1; i < N; i++)
D[i] = A[i] - A[i - 1];
}
// Function that performs
// the range update queries
function update(l, r, x)
{
// Update the ends
// of the range
D[l] += x;
D[r + 1] -= x;
}
// Function that perform all query
// once with modified update Call
function UpdateDiffArray(Start, End, Val, Freq)
{
// For range update, difference
// array is modified
update(Start - 1,
End - 1, Val * Freq);
}
// Function to take queries
function queriesInput(Q)
{
// Traverse the query
for (let i = 0; i < M; i++)
{
// Function Call for updates
UpdateDiffArray(Q[i][0], Q[i][1],
Q[i][2], Q[i][3]);
}
}
// Function to updates the array
// using the difference array
function UpdateArray()
{
// Traverse the array A[]
for (let i = 0; i < N; i++)
{
// 1st Element
if (i == 0)
{
A[i] = D[i];
}
// A[0] or D[0] decides
// values of rest of
// the elements
else
{
A[i] = D[i] + A[i - 1];
}
}
}
// Function that print
// the array
function PrintArray()
{
// Print the element
for (let i = 0; i < N; i++)
{
document.write(A[i] + i +
1 + " ");
}
return;
}
// Function that print the array
// after performing all queries
function printAfterUpdate(A, Q, M)
{
// Create and fill difference
// array for range updates
initializeDiffArray();
queriesInput( Q);
// Now update Array
// A using Difference
// Array
UpdateArray();
// Print updated Array A
// after M queries
PrintArray();
}
// Driver Code
// Given array A[]
let a = [1, 2, 3];
// Queries
let Q = [[1, 2, 1, 4],
[1, 3, 2, 3],
[2, 3, 4, 5]];
// Function Call
printAfterUpdate(a, Q, M);
</script>
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Similar Reads
Queries to count array elements greater than or equal to a given number with updates
Given two arrays arr[] and query[] of sizes N and Q respectively and an integer M, the task for each query, is to count the number of array elements that are greater than or equal to query[i] and decrease all such numbers by M and perform the rest of the queries on the updated array. Examples: Input
15+ min read
Make the array elements equal by performing given operations minimum number of times
Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
7 min read
Queries for count of array elements with values in given range with updates
Given an array arr[] of size N and a matrix Q consisting of queries of the following two types:Â 1 L R : Print the number of elements lying in the range [L, R].2 i x : Set arr[i] = x Examples:Â Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 6}, Q = {{1, {3, 5}}, {1, {2, 4}}, {1, {1, 2}}, {2, {1, 7}}, {1, {1,
15+ min read
Print Array after moving first occurrence of given element to end in given Array for Q queries
Given an array arr[] of N integers and an array query[] having Q integers, the task is to print the array arr[] after moving the first occurrence of query[i] to the end of the array arr[] for each i in the range [0, Q). Example: Input: arr[] = {1, 3, 1, 3}, query[] = {3, 1}Output: 1 3 3 1Explanation
7 min read
Count of Ks in the Array for a given range of indices after array updates for Q queries
Given an array arr[] of N integers, an integer K, and Q queries of the type as explained below: (1, L, R): If the query is of type 1, then find the number of Ks over the range [L, R].(2, P, X): If the query is of type 2, then update the array element at index P to X. The task is to perform the queri
15+ min read
Queries to count array elements from a given range having a single set bit
Given an array arr[] consisting of N integers and a 2D array Q[][] consisting of queries of the following two types: 1 L R: Print the count of numbers from the range [L, R] having only a single set bit.2 X V: Update the array element at Xth index with V.Examples: Input: arr[] = { 12, 11, 16, 2, 32 }
15+ min read
Number of elements less than or equal to a given number in a given subarray | Set 2 (Including Updates)
Given an array 'a[]' and number of queries q there will be two type of queries Query 0 update(i, v) : Two integers i and v which means set a[i] = vQuery 1 count(l, r, k): We need to print number of integers less than equal to k in the subarray l to r. Given a[i], v <= 10000 Examples : Input : arr
12 min read
Minimum increments or decrements by 1 required to make all array elements in AP
Given an array arr[] consisting of N integers, the task is to find the minimum number of increment/decrement by 1 required to be performed on array elements to make all the elements of the given array arr[] in AP. If it is not possible to make the array in AP, then print "-1". Examples: Input: arr[]
11 min read
Count of distinct numbers in an Array in a range for Online Queries using Merge Sort Tree
Given an array arr[] of size N and Q queries of the form [L, R], the task is to find the number of distinct values in this array in the given range. Examples: Input: arr[] = {4, 1, 9, 1, 3, 3}, Q = {{1, 3}, {1, 5}} Output: 3 4 Explanation: For query {1, 3}, elements are {4, 1, 9}. Therefore, count o
15 min read
Print modified array after performing queries to add (i - L + 1) to each element present in the range [L, R]
Given an array arr[] consisting of N 0s (1-based indexing) and another array query[], with each row of the form {L, R}, the task for each query (L, R) is to add a value of (i - L + 1) over the range [L, R] and print the array arr[] obtained after performing all the queries. Examples: Input: arr[] =
13 min read