Print modified array after executing the commands of addition and subtraction
Last Updated :
19 Sep, 2023
Given an array of size 'n' and a given set of commands of size 'm'. Every command consist of four integers q, l, r, k. These commands are of following types:
- If q = 0, add 'k' to all integers in range 'a' to 'b'(1 <= a <= b <= n).
- If q = 1, subtract 'k' to all integers in range 'a' to 'b'(1 <= a <= b <= n).
Note: Initially all the array elements are set to '0' and array indexing is from '1'.
Input : n = 5
commands[] = {{0 1 3 2}, {1 3 5 3},
{0 2 5 1}}
Output : 0 2 -1 -1 -3
Explanation
First command: Add 2 from index 1 to 3
>= 2 2 2 0 0
Second command: Subtract 3 from index 3 to 5
>= 2 2 -1 -3 -3
Third command: Add 1 from index 2 to 5
>= 2 3 0 -2 -2
Simple approach is to execute every command by iterating from left index(l) up-to the right index(r) and update every index according to given command. Time complexity of this approach is O(n*m)
Better approach is to use Fenwick tree(BIT) or segment tree. But it will only optimize upto log(n) time i.e., overall complexity would become O(m*log(n))
Efficient approach is to use simple mathematics. Since all commands can be handled as offline so we can store all updates in our temporary array and then execute it at the last.
- For command '0', add '+k' and '-k' in lth and (r+1)th index elements respectively.
- For command '1', add '-k' and '+k' in the lth and (r+1)th index elements respectively.
After that sum up all the elements for every index 'i' starting from 1st index i.e., ai will contain the sum of all elements from 1 to ith index. This can easily be achieved with the help of dynamic programming.
Implementation:
C++
// C++ program to find modified array
// after executing m commands/queries
#include<bits/stdc++.h>
using namespace std;
// Update function for every command
void updateQuery(int arr[], int n, int q, int l,
int r, int k)
{
// If q == 0, add 'k' and '-k'
// to 'l-1' and 'r' index
if (q == 0){
arr[l-1] += k;
arr[r] += -k;
}
// If q == 1, add '-k' and 'k'
// to 'l-1' and 'r' index
else{
arr[l-1] += -k;
arr[r] += k;
}
return;
}
// Function to generate the final
// array after executing all
// commands
void generateArray(int arr[], int n)
{
// Generate final array with the
// help of DP concept
for (int i = 1; i < n; ++i)
arr[i] += arr[i-1];
return;
}
// Driver program
int main()
{
int n = 5;
int arr[n+1];
//Set all array elements to '0'
memset(arr, 0, sizeof(arr));
int q = 0, l = 1, r = 3, k = 2;
updateQuery(arr, n, q, l, r, k);
q = 1 , l = 3, r = 5, k = 3;
updateQuery(arr, n, q, l, r, k);
q = 0 , l = 2, r = 5, k = 1;
updateQuery(arr, n, q, l, r, k);
// Generate final array
generateArray(arr, n);
// Printing the final modified array
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to find modified array
// after executing m commands/queries
import java.util.Arrays;
class GFG {
// Update function for every command
static void updateQuery(int arr[], int n,
int q, int l, int r, int k)
{
// If q == 0, add 'k' and '-k'
// to 'l-1' and 'r' index
if (q == 0){
arr[l-1] += k;
arr[r] += -k;
}
// If q == 1, add '-k' and 'k'
// to 'l-1' and 'r' index
else{
arr[l-1] += -k;
arr[r] += k;
}
return;
}
// Function to generate the final
// array after executing all
// commands
static void generateArray(int arr[], int n)
{
// Generate final array with the
// help of DP concept
for (int i = 1; i < n; ++i)
arr[i] += arr[i-1];
}
//driver code
public static void main(String arg[])
{
int n = 5;
int arr[] = new int[n+1];
//Set all array elements to '0'
Arrays.fill(arr, 0);
int q = 0, l = 1, r = 3, k = 2;
updateQuery(arr, n, q, l, r, k);
q = 1 ; l = 3; r = 5; k = 3;
updateQuery(arr, n, q, l, r, k);
q = 0 ; l = 2; r = 5; k = 1;
updateQuery(arr, n, q, l, r, k);
// Generate final array
generateArray(arr, n);
// Printing the final modified array
for (int i = 0; i < n; ++i)
System.out.print(arr[i]+" ");
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to find modified array
# after executing m commands/queries
# Update function for every command
def updateQuery(arr, n, q, l, r, k):
# If q == 0, add 'k' and '-k'
# to 'l-1' and 'r' index
if (q == 0):
arr[l - 1] += k
arr[r] += -k
# If q == 1, add '-k' and 'k'
# to 'l-1' and 'r' index
else:
arr[l - 1] += -k
arr[r] += k
return
# Function to generate the final
# array after executing all commands
def generateArray(arr, n):
# Generate final array with the
# help of DP concept
for i in range(1, n):
arr[i] += arr[i - 1]
return
# Driver Code
n = 5
arr = [0 for i in range(n + 1)]
# Set all array elements to '0'
q = 0; l = 1; r = 3; k = 2
updateQuery(arr, n, q, l, r, k)
q, l, r, k = 1, 3, 5, 3
updateQuery(arr, n, q, l, r, k);
q, l, r, k = 0, 2, 5, 1
updateQuery(arr, n, q, l, r, k)
# Generate final array
generateArray(arr, n)
# Printing the final modified array
for i in range(n):
print(arr[i], end = " ")
# This code is contributed by Anant Agarwal.
C#
// Program to find modified
// array after executing
// m commands/queries
using System;
class GFG {
// Update function for every command
static void updateQuery(int[] arr, int n, int q,
int l, int r, int k)
{
// If q == 0, add 'k' and '-k'
// to 'l-1' and 'r' index
if (q == 0) {
arr[l - 1] += k;
arr[r] += -k;
}
// If q == 1, add '-k' and 'k'
// to 'l-1' and 'r' index
else {
arr[l - 1] += -k;
arr[r] += k;
}
return;
}
// Function to generate final
// array after executing all
// commands
static void generateArray(int[] arr, int n)
{
// Generate final array with
// the help of DP concept
for (int i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}
// Driver code
public static void Main()
{
int n = 5;
int[] arr = new int[n + 1];
// Set all array elements to '0'
for (int i = 0; i < arr.Length; i++)
arr[i] = 0;
int q = 0, l = 1, r = 3, k = 2;
updateQuery(arr, n, q, l, r, k);
q = 1;
l = 3;
r = 5;
k = 3;
updateQuery(arr, n, q, l, r, k);
q = 0;
l = 2;
r = 5;
k = 1;
updateQuery(arr, n, q, l, r, k);
// Generate final array
generateArray(arr, n);
// Printing the final modified array
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Anant Agarwal.
JavaScript
<script>
// javascript program to find modified array
// after executing m commands/queries
// Update function for every command
function updateQuery(arr , n , q , l , r , k) {
// If q == 0, add 'k' and '-k'
// to 'l-1' and 'r' index
if (q == 0) {
arr[l - 1] += k;
arr[r] += -k;
}
// If q == 1, add '-k' and 'k'
// to 'l-1' and 'r' index
else {
arr[l - 1] += -k;
arr[r] += k;
}
return;
}
// Function to generate the final
// array after executing all
// commands
function generateArray(arr, n)
{
// Generate final array with the
// help of DP concept
for (i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}
// Driver code
var n = 5;
var arr = Array(n + 1).fill(0);
var q = 0, l = 1, r = 3, k = 2;
updateQuery(arr, n, q, l, r, k);
q = 1;
l = 3;
r = 5;
k = 3;
updateQuery(arr, n, q, l, r, k);
q = 0;
l = 2;
r = 5;
k = 1;
updateQuery(arr, n, q, l, r, k);
// Generate final array
generateArray(arr, n);
// Printing the final modified array
for (i = 0; i < n; i++)
document.write(arr[i] + " ");
// This code is contributed by aashish1995
</script>
Time complexity: O(Max(m,n))
Auxiliary space: O(n)
Similar Reads
Range queries for alternatively addition and subtraction on given Array Given an array arr[] of N integers and Q queries where every row consists of two numbers L and R which denotes the range [L, R], the task is to find the value of alternate addition and subtraction of the array element between range [L, R]. Examples: Input: arr[] = {10, 13, 15, 2, 45, 31, 22, 3, 27},
15+ min read
Constant time range add operation on an array Given an array of size N which is initialized with all zeros. We are given many ranges add queries, which should be applied to this array. We need to print the final updated array as our result. Examples: N = 6 Arr = [0, 0, 0, 0, 0, 0] rangeUpdate1 [0, 2], add 100 Arr = [100, 100, 100, 0, 0, 0] rang
7 min read
Deleting Elements in an Array - Array Operations In this post, we will look into deletion operation in an Array, i.e., how to delete an element from an Array, such as:Delete an Element from the Beginning of an ArrayDelete an Element from a Given Position in an ArrayDelete First Occurrence of Given Element from an ArrayRemove All Occurrences of an
4 min read
Inserting Elements in an Array - Array Operations In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as:Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element at
2 min read
Evaluate an array expression with numbers, + and - Given an array arr[] of string type which consists of strings "+", "-" and Numbers. Find the sum of the given array. Examples : Input : arr[] = {"3", "+", "4", "-", "7", "+", "13"} Output : Value = 13 The value of expression 3+4-7+13 is 13. Input : arr[] = { "2", "+", "1", "-8", "+", "13"} Output :
6 min read