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 <bits/stdc++.h>
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<vector<int> > 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<vector<int> > 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
<script>
// JavaScript program to implement
// the above approach
// Store the number of set bits at
// each position
let prefixCount = [[]];
// Function to precompute the prefix
// count array
function findPrefixCount(arr, size)
{
// Iterate over the range[0, 31]
for(let 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(let 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
function arrayBitwiseAND(size)
{
// Stores the required result
let result = 0;
// Iterate over the range [0, 31]
for(let i = 0; i < 32; i++)
{
// Stores the number of set
// bits at position i
let 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
document.write(result + " ");
}
// Function to update the prefix count
// array in each query
function applyQuery(currentVal, newVal,
size)
{
// Iterate through all the bits
// of the current number
for(let i = 0; i < 32; i++)
{
// Store the bit at position
// i in the current value and
// the new value
let bit1 = ((currentVal >> i) & 1);
let 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
function findbitwiseAND(queries, arr,
N, M)
{
prefixCount = new Array(32);
// Loop to create 2D array using 1D array
for (var i = 0; i < prefixCount.length; i++) {
prefixCount[i] = new Array(2);
}
// Fill the prefix count array
findPrefixCount(arr, N);
// Traverse the queries
for(let i = 0; i < M; i++)
{
// Store the index and
// the new value
let id = queries[i][0];
let newVal = queries[i][1];
// Store the current element
// at the index
let 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
let arr = [ 1, 2, 3, 4, 5 ];
let queries = [[ 0, 2 ], [ 3, 3 ],
[ 4, 2 ]];
let N = arr.length;
let M = queries.length;
findbitwiseAND(queries, arr, N, M);
// This code is contributed by code_hunt.
</script>
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Similar Reads
Queries to calculate Bitwise OR of an array with updates
Given an array arr[ ] consisting of N positive integers and a 2D array Q[][] consisting of queries of the form {i, val}, the task for each query is to replace arr[i] by val and calculate the Bitwise OR of the modified array. Examples: Input: arr[ ]= {1, 2, 3}, Q[ ][] = {{1, 4}, {3, 0}}Output: 7 6Exp
10 min read
Index of kth set bit in a binary array with update queries
Given a binary array arr[] and q queries of following types: k: find the index of the kth set bit i.e. kth 1 in the array.(x, y): Update arr[x] = y where y can either be a 0 or 1. Examples: Input: arr[] = {1, 0, 1, 0, 0, 1, 1, 1}, q = 2 k = 4 (x, y) = (5, 1) Output: Index of 4th set bit: 6 Array aft
15+ min read
Range Update Queries to XOR with 1 in a Binary Array.
Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [
15+ min read
Count of pairs from Array with sum equal to twice their bitwise AND
Given an array arr[], the task is to count the pairs in the array with sum equal to twice their bitwise AND, i.e., A + B = 2 * (A \& B) Examples: Input: arr[] = {1, 1, 3, 4, 4, 5, 7, 8} Output: 2 Explanation: Pairs with sum equal to twice their bitwise AND: {(1, 1), (4, 4)}Input: arr[] = {1, 3,
7 min read
Program to calculate Bitonicity of an Array
Given an array of N integers. The task is to find the Bitonicity of the given array.The Bitonicity of an array arr[] can be defined as: B[i] = 0, if i = 0. = B[i-1] + 1, if arr[i] > arr[i-1] = B[i-1] - 1, if arr[i] < arr[i-1] = B[i-1], if arr[i] = arr[i-1] Bitonicity will be last element of ar
5 min read
Count all pairs of an array which differ in K bits
Given an array of size n and integer k, count all pairs in array which differ in exactly K bits of binary representation of both the numbers.The input arrays have elements with small values and possibly many repetitions. Examples: Input: arr[] = {2, 4, 1, 3, 1} k = 2 Output: 5 Explanation: There are
14 min read
Count pairs from an array whose Bitwise OR is greater than Bitwise AND
Given an array A[] consisting of N integers, the task is to count the number of pairs (i, j) such that i < j, and Bitwise OR of A[i] and A[j] is greater than Bitwise AND of A[i] and A[j]. Examples: Input: A[] = {1, 4, 7}Output: 3Explanation: There are 3 such pairs: (1, 4), (4, 7), (1, 7).1) 1 | 4
10 min read
Bitwise OR of Bitwise AND of all subsets of an Array for Q queries
Given two arrays arr[] of size N and queries[] of size Q, the task is to find the OR of AND of subsets of the array. In each query, you are given an index and a value, you have to replace the value at the given index of the arrays with a given value and print the OR of AND of all subsets of the arra
9 min read
Queries for bitwise AND in the index range [L, R] of the given array
Given an array arr[] of N and Q queries consisting of a range [L, R]. the task is to find the bit-wise AND of all the elements of in that index range.Examples: Input: arr[] = {1, 3, 1, 2, 3, 4}, q[] = {{0, 1}, {3, 5}} Output: 1 0 1 AND 3 = 1 2 AND 3 AND 4 = 0Input: arr[] = {1, 2, 3, 4, 5}, q[] = {{0
8 min read
Bitwise AND of all the elements of array
Given an array, arr[] of N integers, the task is to find out the bitwise AND(&) of all the elements of the array. Examples: Input: arr[] = {1, 3, 5, 9, 11} Output: 1 Input: arr[] = {3, 7, 11, 19, 11} Output: 3 Approach: The idea is to traverse all the array elements and compute the bitwise AND f
4 min read