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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read