Open In App

Queries to calculate Bitwise AND of an array with updates

Last Updated : 29 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
Java Python3 C# JavaScript

Output: 
0 0 2

 

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


Next Article

Similar Reads