Sum of even values and update queries on an array
Last Updated :
22 Jun, 2022
Given an array arr[] of integers and an array q[] of queries.
For the ith query, index = q[i][0] and value = q[i][1]. The task is for every query, update arr[index] = arr[index] + value and then return the sum of all the even elements from the array.
Examples:
Input: arr[] = {1, 2, 3, 4}, q[] = {{0, 1}, {1, -3}, {0, -4}, {3, 2}}
Output: 8 6 2 4
At the beginning, the array is {1, 2, 3, 4}.
After adding 1 to arr[0], the array becomes {2, 2, 3, 4} and the sum of even values is 2 + 2 + 4 = 8.
Add -3 to arr[1], arr[] = {2, -1, 3, 4} and the sum of even values is 2 + 4 = 6.
Add -4 to arr[0], arr[] = {-2, -1, 3, 4} and the sum of even values is -2 + 4 = 2.
Adding 2 to arr[3], arr[] = {-2, -1, 3, 6} and the sum of even values is -2 + 6 = 4.
Input: arr[] = {1, 2, 2, 2}, q[] = {{0, 1}, {1, 1}}
Output: 8 6
Naive Approach: For each query, update the value in the array and calculate the sum of all even values from the array.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the sum of even elements
// after updating value at given index
int EvenSum(vector<int>& A, int index, int value)
{
// Add given value to A[index]
A[index] = A[index] + value;
// To store the sum of even elements
int sum = 0;
for (int i = 0; i < A.size(); i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
return sum;
}
// Function to print the result for every query
void BalanceArray(vector<int>& A, vector<vector<int> >& Q)
{
// Resultant vector that stores
// the result for every query
vector<int> ANS;
int i, sum;
for (i = 0; i < Q.size(); i++) {
int index = Q[i][0];
int value = Q[i][1];
// Get sum of even elements after updating
// value at given index
sum = EvenSum(A, index, value);
// Store sum for each query
ANS.push_back(sum);
}
// Print the result for every query
for (i = 0; i < ANS.size(); i++)
cout << ANS[i] << " ";
}
// Driver code
int main()
{
vector<int> A = { 1, 2, 3, 4 };
vector<vector<int> > Q = { { 0, 1 },
{ 1, -3 },
{ 0, -4 },
{ 3, 2 } };
BalanceArray(A, Q);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the sum of even elements
// after updating value at given index
static int EvenSum(int [] A, int index, int value)
{
// Add given value to A[index]
A[index] = A[index] + value;
// To store the sum of even elements
int sum = 0;
for (int i = 0; i < A.length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
return sum;
}
// Function to print the result for every query
static void BalanceArray(int [] A, int [][] Q)
{
// Resultant vector that stores
// the result for every query
int [] ANS = new int[Q.length];
int i, sum;
for (i = 0; i < Q.length; i++)
{
int index = Q[i][0];
int value = Q[i][1];
// Get sum of even elements after updating
// value at given index
sum = EvenSum(A, index, value);
// Store sum for each query
ANS[i] = sum;
}
// Print the result for every query
for (i = 0; i < ANS.length; i++)
System.out.print(ANS[i] + " ");
}
// Driver code
public static void main(String []args)
{
int [] A = { 1, 2, 3, 4 };
int [][] Q = { { 0, 1 },
{ 1, -3 },
{ 0, -4 },
{ 3, 2 } };
BalanceArray(A, Q);
}
}
// This code is contributed by ihritik
Python3
# Python3 implementation of the approach
# Function to return the sum of even elements
# after updating value at given index
def EvenSum(A, index, value):
# Add given value to A[index]
A[index] = A[index] + value
# To store the sum of even elements
sum = 0
for i in A:
# If current element is even
if (i % 2 == 0):
sum = sum + i
return sum
# Function to print result for every query
def BalanceArray(A,Q):
# Resultant vector that stores
# the result for every query
ANS = []
i, sum = 0, 0
for i in range(len(Q)):
index = Q[i][0]
value = Q[i][1]
# Get sum of even elements after updating
# value at given index
sum = EvenSum(A, index, value)
# Store sum for each query
ANS.append(sum)
# Print the result for every query
for i in ANS:
print(i, end = " ")
# Driver code
A = [1, 2, 3, 4]
Q = [ [0, 1 ],
[1, -3],
[0, -4],
[3, 2 ] ]
BalanceArray(A, Q)
# This code is contributed by mohit kumar 29
C#
// C# implementation of the approach
using System;
public class GFG
{
// Function to return the sum of even elements
// after updating value at given index
static int EvenSum(int[] A, int index, int value)
{
// Add given value to A[index]
A[index] = A[index] + value;
// To store the sum of even elements
int sum = 0;
for (int i = 0; i < A.Length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
return sum;
}
// Function to print the result for every query
static void BalanceArray(int[] A, int[,] Q) {
// Resultant vector that stores
// the result for every query
int[] ANS = new int[Q.GetLength(0)];
int i, sum;
for (i = 0; i < Q.GetLength(0); i++) {
int index = Q[i,0];
int value = Q[i,1];
// Get sum of even elements after updating
// value at given index
sum = EvenSum(A, index, value);
// Store sum for each query
ANS[i] = sum;
}
// Print the result for every query
for (i = 0; i < ANS.Length; i++)
Console.Write(ANS[i] + " ");
}
// Driver code
public static void Main(String[] args)
{
int[] A = { 1, 2, 3, 4 };
int[,] Q = { { 0, 1 }, { 1, -3 }, { 0, -4 }, { 3, 2 } };
BalanceArray(A, Q);
}
}
// This code is contributed by Rajput-Ji.
JavaScript
<script>
// JavaScript implementation of the approach
// Function to return the sum of even elements
// after updating value at given index
function EvenSum(A, index, value)
{
// Add given value to A[index]
A[index] = A[index] + value;
// To store the sum of even elements
var sum = 0;
for (var i = 0; i < A.length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
return sum;
}
// Function to print the result for every query
function BalanceArray(A, Q)
{
// Resultant vector that stores
// the result for every query
var ANS = [];
var i, sum;
for (i = 0; i < Q.length; i++) {
var index = Q[i][0];
var value = Q[i][1];
// Get sum of even elements after updating
// value at given index
sum = EvenSum(A, index, value);
// Store sum for each query
ANS.push(sum);
}
// Print the result for every query
for (i = 0; i < ANS.length; i++)
document.write( ANS[i] + " ");
}
// Driver code
var A = [ 1, 2, 3, 4 ];
var Q = [ [ 0, 1 ],
[ 1, -3 ],
[ 0, -4 ],
[ 3, 2 ] ];
BalanceArray(A, Q);
</script>
Time Complexity: O(n2)
Auxiliary Space: O(n)
Efficient Approach:
- Calculate the sum of Even values in arr[]
- Now if the value of arr[] at given index is even i.e. arr[index] % 2 = 0 then subtract arr[index] from sum.
- Add the given value to arr[index] i.e. arr[index] = arr[index] + value.
- Now check again if the value of arr[index] is even, if yes then add arr[index] to the sum.
- Print the value of sum for every query.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the result for every query
void BalanceArray(vector<int>& A, vector<vector<int> >& Q)
{
vector<int> ANS;
int i, sum = 0;
for (i = 0; i < A.size(); i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
for (i = 0; i < Q.size(); i++) {
int index = Q[i][0];
int value = Q[i][1];
// If element is even then
// remove it from sum
if (A[index] % 2 == 0)
sum = sum - A[index];
A[index] = A[index] + value;
// If the value becomes even after updating
if (A[index] % 2 == 0)
sum = sum + A[index];
// Store sum for each query
ANS.push_back(sum);
}
// Print the result for every query
for (i = 0; i < ANS.size(); i++)
cout << ANS[i] << " ";
}
// Driver code
int main()
{
vector<int> A = { 1, 2, 3, 4 };
vector<vector<int> > Q = { { 0, 1 },
{ 1, -3 },
{ 0, -4 },
{ 3, 2 } };
BalanceArray(A, Q);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to print the result for every query
static void BalanceArray(int [] A, int [][] Q)
{
int [] ANS = new int [A.length];
int i, sum = 0;
for (i = 0; i < A.length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
for (i = 0; i < Q.length; i++)
{
int index = Q[i][0];
int value = Q[i][1];
// If element is even then
// remove it from sum
if (A[index] % 2 == 0)
sum = sum - A[index];
A[index] = A[index] + value;
// If the value becomes even after updating
if (A[index] % 2 == 0)
sum = sum + A[index];
// Store sum for each query
ANS[i]= sum;
}
// Print the result for every query
for (i = 0; i < ANS.length; i++)
System.out.print(ANS[i] + " ");
}
// Driver code
public static void main(String [] args)
{
int [] A = { 1, 2, 3, 4 };
int [][] Q = { { 0, 1 },
{ 1, -3 },
{ 0, -4 },
{ 3, 2 } };
BalanceArray(A, Q);
}
}
// This code is contributed by ihritik
Python3
# Python3 implementation of the approach
# Function to print the result for
# every query
def BalanceArray(A, Q) :
ANS = []
sum = 0
for i in range(len(A)) :
# If current element is even
if (A[i] % 2 == 0) :
sum += A[i];
for i in range(len(Q)) :
index = Q[i][0];
value = Q[i][1];
# If element is even then
# remove it from sum
if (A[index] % 2 == 0) :
sum -= A[index];
A[index] += value;
# If the value becomes even
# after updating
if (A[index] % 2 == 0) :
sum += A[index];
# Store sum for each query
ANS.append(sum);
# Print the result for every query
for i in range(len(ANS)) :
print(ANS[i], end = " ");
# Driver code
if __name__ == "__main__" :
A = [ 1, 2, 3, 4 ];
Q = [ [ 0, 1 ], [ 1, -3 ],
[ 0, -4 ], [ 3, 2 ]];
BalanceArray(A, Q);
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to print the result for every query
static void BalanceArray(int [] A, int [, ] Q)
{
int [] ANS = new int [A.Length];
int i, sum = 0;
for (i = 0; i < A.Length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
for (i = 0; i < Q.GetLength(0); i++)
{
int index = Q[i, 0];
int value = Q[i, 1];
// If element is even then
// remove it from sum
if (A[index] % 2 == 0)
sum = sum - A[index];
A[index] = A[index] + value;
// If the value becomes even after updating
if (A[index] % 2 == 0)
sum = sum + A[index];
// Store sum for each query
ANS[i]= sum;
}
// Print the result for every query
for (i = 0; i < ANS.Length; i++)
Console.Write(ANS[i] + " ");
}
// Driver code
public static void Main()
{
int [] A = { 1, 2, 3, 4 };
int [, ] Q = { { 0, 1 },
{ 1, -3 },
{ 0, -4 },
{ 3, 2 } };
BalanceArray(A, Q);
}
}
// This code is contributed by ihritik
PHP
<?php
// PHP implementation of the approach
// Function to print the result for every query
function BalanceArray($A, &$Q)
{
$ANS = array();
$sum = 0;
for ($i = 0; $i < count($A); $i++)
// If current element is even
if ($A[$i] % 2 == 0)
$sum = $sum + $A[$i];
for ($i = 0; $i < count($Q); $i++)
{
$index = $Q[$i][0];
$value = $Q[$i][1];
// If element is even then
// remove it from sum
if ($A[$index] % 2 == 0)
$sum = $sum - $A[$index];
$A[$index] = $A[$index] + $value;
// If the value becomes even after updating
if ($A[$index] % 2 == 0)
$sum = $sum + $A[$index];
// Store sum for each query
array_push($ANS,$sum);
}
// Print the result for every query
for ($i = 0; $i < count($ANS); $i++)
echo $ANS[$i] . " ";
}
// Driver code
$A = array( 1, 2, 3, 4 );
$Q = array(array( 0, 1 ),
array( 1, -3 ),
array( 0, -4 ),
array( 3, 2 ));
BalanceArray($A, $Q);
// This code is contributed by chandan_jnu
?>
JavaScript
<script>
// JavaScript implementation of the approach
// Function to print the result for every query
function BalanceArray(A, Q)
{
var ANS = [];
var i, sum = 0;
for (i = 0; i < A.length; i++)
// If current element is even
if (A[i] % 2 == 0)
sum = sum + A[i];
for (i = 0; i < Q.length; i++) {
var index = Q[i][0];
var value = Q[i][1];
// If element is even then
// remove it from sum
if (A[index] % 2 == 0)
sum = sum - A[index];
A[index] = A[index] + value;
// If the value becomes even after updating
if (A[index] % 2 == 0)
sum = sum + A[index];
// Store sum for each query
ANS.push(sum);
}
// Print the result for every query
for (i = 0; i < ANS.length; i++)
document.write( ANS[i] + " ");
}
// Driver code
var A = [ 1, 2, 3, 4 ];
var Q = [ [ 0, 1 ],
[ 1, -3 ],
[ 0, -4 ],
[ 3, 2 ] ];
BalanceArray(A, Q);
</script>
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Sum and Update Queries on 2D Matrix
Given a 2D matrix mat[][] of size NXN with all its elements initialized to 0, the task is to answer Q queries. Each query[i] can be one of the following types: Type 1 [1, x, y, ele]: Update the value of cell(x, y) to val.Type 2 [2, x1, y1 ,x2, y2]: Print the sum of the submatrix (x1, y1) to (x2, y2)
12 min read
Queries to calculate Bitwise AND of an array with updates
Given an array arr[] consisting of N positive integers and a 2D array Q[][] consisting of queries of the type {i, val}, the task for each query is to replace arr[i] by val and calculate the Bitwise AND of the modified array. Examples: Input: arr[] = {1, 2, 3, 4, 5}, Q[][] = {{0, 2}, {3, 3}, {4, 2}}O
15+ min read
Print the sum of array after doing k queries on the array
Given an array, arr[] of size n. Calculate the sum of arr[] by performing k queries on arr[], such that we have to add an element given in array y[], on the basis of the boolean value given in array check[]. For every index i (0<= i <= n - 1): If check[i] = true, Add y[i] to all the odd number
10 min read
Find sum of all unique elements in the array for K queries
Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based index
8 min read
Sum of odd Array elements after each update query
Given an integer array Arr[] of length N and an array Queries[] of length Q where Queries[i] = [valuei, indexi]. For each query i, update Arr[indexi] = Arr[indexi] + valuei, then print the sum of the all the odd values of Arr[]. Examples: Input: N = 4, Arr = [1,2,3,5], Q = 4, Queries = [[1,0],[-3,1]
15+ min read
Increasing Decreasing Update Queries (Akku and Arrays)
Akku has solved many problems, she is a genius. One day her friend gave her an Array of sizes n and asked her to perform some queries of the following type: Each query consists of three integers 1 A B: Update the Array at index A by value B2 A B: if the subarray from index A to B (both inclusive) is
15+ min read
Count of odd and even sum pairs in an array
Given an array arr[] of N positive integers, the task is to find the number of pairs with odd sum and the number of pairs with even sum.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: Odd pairs = 6 Even pairs = 4Input: arr[] = {7, 4, 3, 2} Output: Odd pairs = 4 Even pairs = 2 Naive Approach: The na
8 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
Sum of even elements of an Array using Recursion
Given an array arr[] of integers, the task is to find the sum of even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 Approach: Write a recursive function that takes the array as an argument wit
5 min read
Binary Indexed Tree : Range Updates and Point Queries
Given an array arr[0..n-1]. The following operations need to be performed. update(l, r, val): Add âvalâ to all the elements in the array from [l, r].getElement(i): Find element in the array indexed at âiâ. Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be
15+ min read