Bitwise operations on Subarrays of size K | C ++ program for minimum values of each bitwise AND operation on elements of subarray of size K ; Function to convert bit array to decimal number ; Function to find minimum values of each bitwise AND operation on element of subarray of size K ; Maintain an integer array bit [ ] of size 32 all initialized to 0 ; Create a sliding window of size k ; Function call ; Perform operation to removed element ; Perform operation to add element ; Taking minimum value ; Return the result ; Driver Code ; Given array arr [ ] ; Given subarray size K ; Function Call
#include <iostream> NEW_LINE using namespace std ; int build_num ( int bit [ ] , int k ) { int ans = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) if ( bit [ i ] == k ) ans += ( 1 << i ) ; return ans ; } int minimumAND ( int arr [ ] , int n , int k ) { int bit [ 32 ] = { 0 } ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) bit [ j ] ++ ; } } int min_and = build_num ( bit , k ) ; for ( int i = k ; i < n ; i ++ ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i - k ] & ( 1 << j ) ) bit [ j ] -- ; } for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) bit [ j ] ++ ; } min_and = min ( build_num ( bit , k ) , min_and ) ; } return min_and ; } int main ( ) { int arr [ ] = { 2 , 5 , 3 , 6 , 11 , 13 } ; int k = 3 ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << minimumAND ( arr , n , k ) ; return 0 ; }