Related Articles

# Queries to calculate Bitwise AND of an array with updates

• Last Updated : 29 May, 2021

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}}
Output: 0 0 2
Explanation:
Query 1: Update A[0] to 2, then the array modifies to {2, 2, 3, 4, 5}. The Bitwise AND of all the elements is 0.
Query 2: Update A[3] to 3, then the array modifies to {2, 2, 3, 3, 5}. The Bitwise AND of all the elements is 0.
Query 3: Update A[4] to 2, then the modified array, A[]={2, 2, 3, 3, 2}. The Bitwise AND of all the elements is 2.

Input: arr[] = {1, 2, 3}, Q[][] = {{1, 5}, {2, 4}}
Output: 1 0

Naive Approach: The simplest approach is to solve the given problem is to update the array element for each query and then find the bitwise AND of all the array elements by traversing the array in each query.

Time Complexity: O(N * Q)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using an auxiliary array, say bitCount[][] of size 32 * N to store the sum of set bits at position i till the jth index of the array. So, bitCount[i][N – 1] represents the total sum of set bits at position i using all the array elements. Follow the steps below to solve the problem:

• Initialize an array bitCount[32][N] to store the set bits of the array elements.
• Iterate over the range [0, 31] using the variable i and perform the following steps:
• If the value of A[0] is set at the ith position, then update bitCount[i][0] to 1. Otherwise, update it to 0.
• Traverse the array A[] in the range [1, N – 1] using the variable j and perform the following steps:
• If the value of A[j] is set at ith position, then update bitCount[i][j] to 1.
• Add the value of bitCount[i][j – 1] to bitCount[i][j].
• Traverse the given array of queries Q[][] and perform the following steps:
• Initialize a variable, say res as 0, to store the result of the current query.
• Store the current value at the given index in currentVal and the new value in newVal.
• Iterate over the range [0, 31] using the variable i
• If newVal is set at index i and currentVal is not set, then increment prefix[i][N – 1] by 1.
• Otherwise, if currentVal is set at index i and newVal is not set, then decrement prefix[i][N – 1] by 1.
• If the value of prefix[i][N – 1] is equal to N, set this bit in res.
• After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Store the number of set bits at``// each position``int` `prefixCount[32][10000];` `// Function to precompute the prefix``// count array``void` `findPrefixCount(vector<``int``> arr,``                     ``int` `size)``{``    ``// Iterate over the range[0, 31]``    ``for` `(``int` `i = 0; i < 32; i++) {` `        ``// Set the bit at position i``        ``// if arr[0] is set at position i``        ``prefixCount[i][0]``            ``= ((arr[0] >> i) & 1);` `        ``// Traverse the array and``        ``// take prefix sum``        ``for` `(``int` `j = 1; j < size; j++) {` `            ``// Update prefixCount[i][j]``            ``prefixCount[i][j]``                ``= ((arr[j] >> i) & 1);``            ``prefixCount[i][j]``                ``+= prefixCount[i][j - 1];``        ``}``    ``}``}` `// Function to find the Bitwise AND``// of all array elements``void` `arrayBitwiseAND(``int` `size)``{``    ``// Stores the required result``    ``int` `result = 0;` `    ``// Iterate over the range [0, 31]``    ``for` `(``int` `i = 0; i < 32; i++) {` `        ``// Stores the number of set``        ``// bits at position i``        ``int` `temp = prefixCount[i]``                              ``[size - 1];` `        ``// If temp is N, then set ith``        ``// position in the result``        ``if` `(temp == size)``            ``result = (result | (1 << i));``    ``}` `    ``// Print the result``    ``cout << result << ``" "``;``}` `// Function to update the prefix count``// array in each query``void` `applyQuery(``int` `currentVal, ``int` `newVal,``                ``int` `size)``{``    ``// Iterate through all the bits``    ``// of the current number``    ``for` `(``int` `i = 0; i < 32; i++) {` `        ``// Store the bit at position``        ``// i in the current value and``        ``// the new value``        ``int` `bit1 = ((currentVal >> i) & 1);``        ``int` `bit2 = ((newVal >> i) & 1);` `        ``// If bit2 is set and bit1 is``        ``// unset, then increase the``        ``// set bits at position i by 1``        ``if` `(bit2 > 0 && bit1 == 0)``            ``prefixCount[i][size - 1]++;` `        ``// If bit1 is set and bit2 is``        ``// unset, then decrease the``        ``// set bits at position i by 1``        ``else` `if` `(bit1 > 0 && bit2 == 0)``            ``prefixCount[i][size - 1]--;``    ``}``}` `// Function to find the bitwise AND``// of the array after each query``void` `findbitwiseAND(``    ``vector > queries,``    ``vector<``int``> arr, ``int` `N, ``int` `M)``{``    ``// Fill the prefix count array``    ``findPrefixCount(arr, N);` `    ``// Traverse the queries``    ``for` `(``int` `i = 0; i < M; i++) {` `        ``// Store the index and``        ``// the new value``        ``int` `id = queries[i][0];``        ``int` `newVal = queries[i][1];` `        ``// Store the current element``        ``// at the index``        ``int` `currentVal = arr[id];` `        ``// Update the array element``        ``arr[id] = newVal;` `        ``// Apply the changes to the``        ``// prefix count array``        ``applyQuery(currentVal, newVal, N);` `        ``// Print the bitwise AND of``        ``// the modified array``        ``arrayBitwiseAND(N);``    ``}``}` `// Driver Code``int` `main()``{``    ``vector<``int``> arr{ 1, 2, 3, 4, 5 };``    ``vector > queries{ { 0, 2 },``                                  ``{ 3, 3 },``                                  ``{ 4, 2 } };``    ``int` `N = arr.size();``    ``int` `M = queries.size();``    ``findbitwiseAND(queries, arr, N, M);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `class` `GFG{` `// Store the number of set bits at``// each position``static` `int` `prefixCount[][];` `// Function to precompute the prefix``// count array``static` `void` `findPrefixCount(``int` `arr[], ``int` `size)``{``    ` `    ``// Iterate over the range[0, 31]``    ``for``(``int` `i = ``0``; i < ``32``; i++)``    ``{``        ` `        ``// Set the bit at position i``        ``// if arr[0] is set at position i``        ``prefixCount[i][``0``] = ((arr[``0``] >> i) & ``1``);` `        ``// Traverse the array and``        ``// take prefix sum``        ``for``(``int` `j = ``1``; j < size; j++)``        ``{``            ` `            ``// Update prefixCount[i][j]``            ``prefixCount[i][j] = ((arr[j] >> i) & ``1``);``            ``prefixCount[i][j] += prefixCount[i][j - ``1``];``        ``}``    ``}``}` `// Function to find the Bitwise AND``// of all array elements``static` `void` `arrayBitwiseAND(``int` `size)``{``    ` `    ``// Stores the required result``    ``int` `result = ``0``;` `    ``// Iterate over the range [0, 31]``    ``for``(``int` `i = ``0``; i < ``32``; i++)``    ``{``        ` `        ``// Stores the number of set``        ``// bits at position i``        ``int` `temp = prefixCount[i][size - ``1``];` `        ``// If temp is N, then set ith``        ``// position in the result``        ``if` `(temp == size)``            ``result = (result | (``1` `<< i));``    ``}` `    ``// Print the result``    ``System.out.print(result + ``" "``);``}` `// Function to update the prefix count``// array in each query``static` `void` `applyQuery(``int` `currentVal, ``int` `newVal,``                       ``int` `size)``{``    ` `    ``// Iterate through all the bits``    ``// of the current number``    ``for``(``int` `i = ``0``; i < ``32``; i++)``    ``{``        ` `        ``// Store the bit at position``        ``// i in the current value and``        ``// the new value``        ``int` `bit1 = ((currentVal >> i) & ``1``);``        ``int` `bit2 = ((newVal >> i) & ``1``);` `        ``// If bit2 is set and bit1 is``        ``// unset, then increase the``        ``// set bits at position i by 1``        ``if` `(bit2 > ``0` `&& bit1 == ``0``)``            ``prefixCount[i][size - ``1``]++;` `        ``// If bit1 is set and bit2 is``        ``// unset, then decrease the``        ``// set bits at position i by 1``        ``else` `if` `(bit1 > ``0` `&& bit2 == ``0``)``            ``prefixCount[i][size - ``1``]--;``    ``}``}` `// Function to find the bitwise AND``// of the array after each query``static` `void` `findbitwiseAND(``int` `queries[][], ``int` `arr[],``                           ``int` `N, ``int` `M)``{` `    ``prefixCount = ``new` `int``[``32``][``10000``];``    ` `    ``// Fill the prefix count array``    ``findPrefixCount(arr, N);` `    ``// Traverse the queries``    ``for``(``int` `i = ``0``; i < M; i++)``    ``{``        ` `        ``// Store the index and``        ``// the new value``        ``int` `id = queries[i][``0``];``        ``int` `newVal = queries[i][``1``];` `        ``// Store the current element``        ``// at the index``        ``int` `currentVal = arr[id];` `        ``// Update the array element``        ``arr[id] = newVal;` `        ``// Apply the changes to the``        ``// prefix count array``        ``applyQuery(currentVal, newVal, N);` `        ``// Print the bitwise AND of``        ``// the modified array``        ``arrayBitwiseAND(N);``    ``}``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5` `};``    ``int` `queries[][] = { { ``0``, ``2` `}, { ``3``, ``3` `},``                        ``{ ``4``, ``2` `} };``    ``int` `N = arr.length;``    ``int` `M = queries.length;``    ` `    ``findbitwiseAND(queries, arr, N, M);``}``}` `// This code is contributed by Kingash`

## Python3

 `# Python3 program for the above approach` `# Store the number of set bits at``# each position``prefixCount ``=` `[[``0` `for` `x ``in` `range``(``32``)]``                  ``for` `y ``in` `range``(``10000``)]` `# Function to precompute the prefix``# count array``def` `findPrefixCount(arr, size):``    ` `    ``# Iterate over the range[0, 31]``    ``for` `i ``in` `range``(``32``):` `        ``# Set the bit at position i``        ``# if arr[0] is set at position i``        ``prefixCount[i][``0``] ``=` `((arr[``0``] >> i) & ``1``)` `        ``# Traverse the array and``        ``# take prefix sum``        ``for` `j ``in` `range``(``1``, size):` `            ``# Update prefixCount[i][j]``            ``prefixCount[i][j] ``=` `((arr[j] >> i) & ``1``)``            ``prefixCount[i][j] ``+``=` `prefixCount[i][j ``-` `1``]` `# Function to find the Bitwise AND``# of all array elements``def` `arrayBitwiseAND(size):` `    ``# Stores the required result``    ``result ``=` `0` `    ``# Iterate over the range [0, 31]``    ``for` `i ``in` `range``(``32``):` `        ``# Stores the number of set``        ``# bits at position i``        ``temp ``=` `prefixCount[i][size ``-` `1``]` `        ``# If temp is N, then set ith``        ``# position in the result``        ``if` `(temp ``=``=` `size):``            ``result ``=` `(result | (``1` `<< i))` `    ``# Print the result``    ``print``(result, end ``=` `" "``)` `# Function to update the prefix count``# array in each query``def` `applyQuery(currentVal, newVal, size):` `    ``# Iterate through all the bits``    ``# of the current number``    ``for` `i ``in` `range``(``32``):` `        ``# Store the bit at position``        ``# i in the current value and``        ``# the new value``        ``bit1 ``=` `((currentVal >> i) & ``1``)``        ``bit2 ``=` `((newVal >> i) & ``1``)` `        ``# If bit2 is set and bit1 is``        ``# unset, then increase the``        ``# set bits at position i by 1``        ``if` `(bit2 > ``0` `and` `bit1 ``=``=` `0``):``            ``prefixCount[i][size ``-` `1``] ``+``=` `1` `        ``# If bit1 is set and bit2 is``        ``# unset, then decrease the``        ``# set bits at position i by 1``        ``elif` `(bit1 > ``0` `and` `bit2 ``=``=` `0``):``            ``prefixCount[i][size ``-` `1``] ``-``=` `1` `# Function to find the bitwise AND``# of the array after each query``def` `findbitwiseAND(queries, arr, N,  M):` `    ``# Fill the prefix count array``    ``findPrefixCount(arr, N)` `    ``# Traverse the queries``    ``for` `i ``in` `range``(M):` `        ``# Store the index and``        ``# the new value``        ``id` `=` `queries[i][``0``]``        ``newVal ``=` `queries[i][``1``]` `        ``# Store the current element``        ``# at the index``        ``currentVal ``=` `arr[``id``]` `        ``# Update the array element``        ``arr[``id``] ``=` `newVal` `        ``# Apply the changes to the``        ``# prefix count array``        ``applyQuery(currentVal, newVal, N)` `        ``# Print the bitwise AND of``        ``# the modified array``        ``arrayBitwiseAND(N)` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``4``, ``5` `]``    ``queries ``=` `[ [ ``0``, ``2` `],``                ``[ ``3``, ``3` `],``                ``[ ``4``, ``2` `] ]``    ``N ``=` `len``(arr)``    ``M ``=` `len``(queries)``    ` `    ``findbitwiseAND(queries, arr, N, M)` `# This code is contributed by ukasp`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Store the number of set bits at``// each position``static` `int` `[,]prefixCount = ``new` `int``[32, 10000];` `// Function to precompute the prefix``// count array``static` `void` `findPrefixCount(List<``int``> arr,``                            ``int` `size)``{``    ` `    ``// Iterate over the range[0, 31]``    ``for``(``int` `i = 0; i < 32; i++)``    ``{``        ` `        ``// Set the bit at position i``        ``// if arr[0] is set at position i``        ``prefixCount[i, 0] = ((arr[0] >> i) & 1);` `        ``// Traverse the array and``        ``// take prefix sum``        ``for``(``int` `j = 1; j < size; j++)``        ``{``            ` `            ``// Update prefixCount[i][j]``            ``prefixCount[i, j] = ((arr[j] >> i) & 1);``            ``prefixCount[i, j] += prefixCount[i, j - 1];``        ``}``    ``}``}` `// Function to find the Bitwise AND``// of all array elements``static` `void` `arrayBitwiseAND(``int` `size)``{``    ` `    ``// Stores the required result``    ``int` `result = 0;` `    ``// Iterate over the range [0, 31]``    ``for``(``int` `i = 0; i < 32; i++)``    ``{``        ` `        ``// Stores the number of set``        ``// bits at position i``        ``int` `temp = prefixCount[i, size - 1];` `        ``// If temp is N, then set ith``        ``// position in the result``        ``if` `(temp == size)``            ``result = (result | (1 << i));``    ``}``    ` `    ``// Print the result``    ``Console.Write(result + ``" "``);``}` `// Function to update the prefix count``// array in each query``static` `void` `applyQuery(``int` `currentVal, ``int` `newVal,``                       ``int` `size)``{``    ` `    ``// Iterate through all the bits``    ``// of the current number``    ``for``(``int` `i = 0; i < 32; i++)``    ``{``        ` `        ``// Store the bit at position``        ``// i in the current value and``        ``// the new value``        ``int` `bit1 = ((currentVal >> i) & 1);``        ``int` `bit2 = ((newVal >> i) & 1);` `        ``// If bit2 is set and bit1 is``        ``// unset, then increase the``        ``// set bits at position i by 1``        ``if` `(bit2 > 0 && bit1 == 0)``            ``prefixCount[i, size - 1]++;` `        ``// If bit1 is set and bit2 is``        ``// unset, then decrease the``        ``// set bits at position i by 1``        ``else` `if` `(bit1 > 0 && bit2 == 0)``            ``prefixCount[i, size - 1]--;``    ``}``}` `// Function to find the bitwise AND``// of the array after each query``static` `void` `findbitwiseAND(``int` `[,]queries,``                      ``List<``int``> arr, ``int` `N, ``int` `M)``{``    ` `    ``// Fill the prefix count array``    ``findPrefixCount(arr, N);` `    ``// Traverse the queries``    ``for``(``int` `i = 0; i < M; i++)``    ``{``        ` `        ``// Store the index and``        ``// the new value``        ``int` `id = queries[i,0];``        ``int` `newVal = queries[i,1];` `        ``// Store the current element``        ``// at the index``        ``int` `currentVal = arr[id];` `        ``// Update the array element``        ``arr[id] = newVal;` `        ``// Apply the changes to the``        ``// prefix count array``        ``applyQuery(currentVal, newVal, N);` `        ``// Print the bitwise AND of``        ``// the modified array``        ``arrayBitwiseAND(N);``    ``}``}` `// Driver Code``public` `static` `void` `Main()``{``    ``List<``int``> arr = ``new` `List<``int``>(){ 1, 2, 3, 4, 5 };``    ``int` `[,] queries = ``new` `int` `[3, 2]{ { 0, 2 },``                                      ``{ 3, 3 },``                                      ``{ 4, 2 } };` `    ``int` `N = arr.Count;``    ``int` `M = 3;``    ` `    ``findbitwiseAND(queries, arr, N, M);``}``}` `// This code is contributed by ipg2016107`

## Javascript

 ``
Output:
`0 0 2`

Time Complexity: O(N + M)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up