Queries to calculate Bitwise AND of an array with updates | Store the number of set bits at each position ; Function to precompute the prefix count array ; Iterate over the range [ 0 , 31 ] ; Set the bit at position i if arr [ 0 ] is set at position i ; Traverse the array and take prefix sum ; Update prefixCount [ i ] [ j ] ; Function to find the Bitwise AND of all array elements ; Stores the required result ; Iterate over the range [ 0 , 31 ] ; Stores the number of set bits at position i ; If temp is N , then set ith position in the result ; Print the result ; Function to update the prefix count array in each query ; Iterate through all the bits of the current number ; Store the bit at position i in the current value and the new value ; If bit2 is set and bit1 is unset , then increase the set bits at position i by 1 ; If bit1 is set and bit2 is unset , then decrease the set bits at position i by 1 ; Function to find the bitwise AND of the array after each query ; Fill the prefix count array ; Traverse the queries ; Store the index and the new value ; Store the current element at the index ; Update the array element ; Apply the changes to the prefix count array ; Print the bitwise AND of the modified array ; Driver code
let prefixCount = [ [ ] ] ; function findPrefixCount ( arr , size ) { for ( let i = 0 ; i < 32 ; i ++ ) { prefixCount [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; for ( let j = 1 ; j < size ; j ++ ) { prefixCount [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; prefixCount [ i ] [ j ] += prefixCount [ i ] [ j - 1 ] ; } } } function arrayBitwiseAND ( size ) { let result = 0 ; for ( let i = 0 ; i < 32 ; i ++ ) { let temp = prefixCount [ i ] [ size - 1 ] ; if ( temp == size ) result = ( result | ( 1 << i ) ) ; } document . write ( result + " " ) ; } function applyQuery ( currentVal , newVal , size ) { for ( let i = 0 ; i < 32 ; i ++ ) { let bit1 = ( ( currentVal >> i ) & 1 ) ; let bit2 = ( ( newVal >> i ) & 1 ) ; if ( bit2 > 0 && bit1 == 0 ) prefixCount [ i ] [ size - 1 ] ++ ; else if ( bit1 > 0 && bit2 == 0 ) prefixCount [ i ] [ size - 1 ] -- ; } } function findbitwiseAND ( queries , arr , N , M ) { prefixCount = new Array ( 32 ) ; for ( var i = 0 ; i < prefixCount . length ; i ++ ) { prefixCount [ i ] = new Array ( 2 ) ; } findPrefixCount ( arr , N ) ; for ( let i = 0 ; i < M ; i ++ ) { let id = queries [ i ] [ 0 ] ; let newVal = queries [ i ] [ 1 ] ; let currentVal = arr [ id ] ; arr [ id ] = newVal ; applyQuery ( currentVal , newVal , N ) ; arrayBitwiseAND ( N ) ; } } 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 ) ;