Skip to content
Related Articles

Related Articles

Find largest index till which Bitwise AND of elements is at least X for Q queries

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 23 Jun, 2022
View Discussion
Improve Article
Save Article

Given array of integers arr[] and queries[] of size N and Q, the task is to find the largest index for each query Q[i] such that bitwise AND of each element from starting till that index is at least Q[i], i.e. (arr[1] & arr[2] &. . .& arr[k]) ≥ Q[i].

Example:

Input: arr[ ] = [3, 7, 9, 16] , queries[] = [ 2, 1 ]
Output: 2 3
Explanation: Answer for the first query is 2. Since, (3 & 7) = 3 >= 2. So largest index is 2. 
Answer for the second query is 3. Since, (3 & 7 & 9) = 1 >= 1. So largest index is 3.

Input: arr[ ] = [1, 2, 3], queries[ ] = [10] 
Output: -1
Explanation: Since the query 10 is large then none of the bitwise And subarray from 1 to index is possible, 
So answer is -1.

 

Naive Approach: The basic idea of the approach is to iterate through the array arr[] for each query and find the largest index that meets the criteria.

Follow the steps mentioned below to solve the problem:

  • Initialize an empty array answer to store the answer to the queries.
  • Iterate from 0 to Q (Let’s say the iterator is i).
    • Declare a variable named bit_and and initialize it with arr[0].
    • If arr[0] is less than X, add 0 to the answer and continue
    • Declare a variable count and initialize it with 1 to store the answer for each query.
    • Iterate from 1 to length of arr(Let’s say the iterator is j).
      • Update bit_and with arr[j] & bit_and.
      • If bit_and is greater than equal to X,  increment count by 1 and continue.
      • Else, break.
    • Add count to the answer.
  • Return answer.

Below is the implementation of the above approach : 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the largest index
vector<int> bitwiseAnd(int n, int q,
                       vector<int>& arr,
                       vector<int>& queries)
{
    vector<int> answer;
    for (int i = 0; i < q; i++) {
        int x = queries[i];
        int bit_and = arr[0];
        if (arr[0] < x) {
            answer.push_back(0);
            continue;
        }
 
        int count = 1;
 
        // Checking for the largest index
        for (int j = 1; j < n; j++) {
            bit_and = bit_and & arr[j];
            if (bit_and >= x) {
                count++;
                continue;
            }
            else {
                break;
            }
        }
        answer.push_back(count);
    }
    return answer;
}
 
//Driver code
int main()
{
    int N = 4, Q = 2;
    vector<int> arr = { 3, 7, 9, 16 };
    vector<int> queries = { 2, 1 };
     
    // Function call
    vector<int> ans
        = bitwiseAnd(N, Q, arr, queries);
    for (auto& i : ans)
        cout << i << " ";
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG
{
    // Function to find the largest index
static ArrayList<Integer> bitwiseAnd(int n,int q,int[] arr,int[] queries)
{
    ArrayList<Integer> answer = new ArrayList<Integer>();
    for (int i = 0; i < q; i++) {
        int x = queries[i];
        int bit_and = arr[0];
        if (arr[0] < x) {
            answer.add(0);
            continue;
        }
 
        int count = 1;
 
        // Checking for the largest index
        for (int j = 1; j < n; j++) {
            bit_and = bit_and & arr[j];
            if (bit_and >= x) {
                count++;
                continue;
            }
            else {
                break;
            }
        }
        answer.add(count);
    }
    return answer;
}
 
// Driver code
public static void main(String args[])
{
    int N = 4, Q = 2;
    int[] arr = {3, 7, 9, 16};
    int[] queries = {2, 1};
     
    // Function call
    ArrayList<Integer>ans = bitwiseAnd(N, Q, arr, queries);
    for (int i : ans)
        System.out.printf("%d ",i);
}
}
 
// This code is contributed by shinjanpatra


Python3




# Python code for the above approach
 
# Function to find the largest index
def bitwiseAnd(n, q, arr,queries):
 
    answer =[]
    for i in range(q):
        x = queries[i]
        bit_and = arr[0]
        if (arr[0] < x) :
            answer.append(0)
            continue
 
        count = 1
 
        # Checking for the largest index
        for j in range(1,n):
            bit_and = bit_and & arr[j]
            if (bit_and >= x):
                count += 1
                continue
 
            else :
                break
        answer.append(count)
    return answer
 
# Driver code
N,Q = 4,2
arr = [3, 7, 9, 16]
queries = [2, 1]
 
# Function call
ans = bitwiseAnd(N, Q, arr, queries)
for i in ans :
    print(i,end=" ")
 
# This code is contributed by shinjanpatra


C#




// C# program to implement above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  // Function to find the largest index
  static void bitwiseAnd(int n, int q, int[]arr,
                         int[]queries)
  {
 
    List<int> answer = new List<int>();
    for (int i = 0; i < q; i++) {
      int x = queries[i];
      int bit_and = arr[0];
      if (arr[0] < x) {
        answer.Add(0);
        continue;
      }
 
      int count = 1;
 
      // Checking for the largest index
      for (int j = 1; j < n; j++) {
        bit_and = bit_and & arr[j];
        if (bit_and >= x) {
          count++;
          continue;
        }
        else {
          break;
        }
      }
      Console.Write(count + " ");
 
    }
 
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 4, Q = 2;
    int[] arr = { 3, 7, 9, 16 };
    int[] queries = { 2, 1 };
 
    // Function call
    bitwiseAnd(N, Q, arr, queries);
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
// JavaScript code for the above approach
 
// Function to find the largest index
function bitwiseAnd(n, q, arr,
                        queries)
{
    let answer =[];
    for (let i = 0; i < q; i++) {
        let x = queries[i];
        let bit_and = arr[0];
        if (arr[0] < x) {
            answer.push(0);
            continue;
        }
 
        let count = 1;
 
        // Checking for the largest index
        for (let j = 1; j < n; j++) {
            bit_and = bit_and & arr[j];
            if (bit_and >= x) {
                count++;
                continue;
            }
            else {
                break;
            }
        }
        answer.push(count);
    }
    return answer;
}
 
// Driver code
    let N = 4, Q = 2;
    let arr = [3, 7, 9, 16];
    let queries = [2, 1];
     
    // Function call
    let ans
        = bitwiseAnd(N, Q, arr, queries);
    for ( i of ans)
        document.write( i + " ");
 
      // This code is contributed by Potta Lokesh
 
    </script>


 
 

Output

2 3 

 

Time Complexity: O(N * Q)
Auxiliary Space: O(1)

 

Efficient Approach: The idea for efficient approach is based on the following observation:

 

The bitwise AND operation when applied from start of array to ith index is monotonically decreasing for an array. So use pre AND operation on the array and then use binary search to find the largest index having a given value.

 

Follow the steps mentioned below to solve the problem:

 

  • Declare an empty array named answer to store the answers to the queries.
  • Declare an array of size N named prefix to store the prefix AND of the array till ith index.
  • Update prefix[0] with arr[0].
  • Iterate from 1 to N(Let’s say the iterator is j).
    • Update prefix[j] with arr[j] & prefix[j-1].
  • Iterate from 0 to Q (Let’s say the iterator is i).
    • Declare 2 variables named st and end and initialize them with 0 and N – 1. Respectively.
    • Declare a variable named count and initialize it with 0.
    • Start a while loop with condition st is less than equal to END.
      • Declare a variable named mid and initialize it with (st + end) / 2.
      • If prefix[mid] is greater than equal to queries[mid], update count as mid+1 and st as mid+1.
      • Else, update end as mid-1.
    • Add count to the answer.
  • Return answer.

 

Below is the implementation of the above approach.

 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the largest index
vector<int> bitwiseAnd(int n, int q,
                       vector<int>& arr,
                       vector<int>& queries)
{
    vector<int> answer;
    vector<int> prefix(n, 0);
    prefix[0] = arr[0];
 
    // Constructing the prefix
    // bitwise and array.
    for (int i = 1; i < n; i++) {
        prefix[i] = prefix[i - 1] & arr[i];
    }
 
    for (int i = 0; i < q; i++) {
        int x = queries[i];
        int st = 0;
        int end = n - 1;
        int count = 0;
 
        // Binary Searching the largest index
        while (st <= end) {
            int mid = (st + end) / 2;
            if (prefix[mid] >= x) {
                count = mid + 1;
                st = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        answer.push_back(count);
    }
    return answer;
}
 
// Driver code
int main()
{
    int N = 4, Q = 2;
    vector<int> arr = { 3, 7, 9, 16 };
    vector<int> queries = { 2, 1 };
     
    // Function call
    vector<int> ans
        = bitwiseAnd(N, Q, arr, queries);
    for (auto& i : ans)
        cout << i << " ";
    return 0;
}


Java




// Java code to implement the approach
 
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG
{
  // Function to find the largest index
  static ArrayList<Integer> bitwiseAnd(int n,int q,int[] arr,int[] queries)
  {
    ArrayList<Integer> answer = new ArrayList<Integer>();
    ArrayList<Integer> prefix = new ArrayList<Integer>();
    for(int i=0;i<n;i++)
    {
      prefix.add(0);
    }
    prefix.set(0,arr[0]);
 
    // Constructing the prefix
    // bitwise and array.
    for (int i = 1; i < n; i++)
    {
      prefix.set(i,prefix.get(i-1) & arr[i]);
    }
 
    for (int i = 0; i < q; i++)
    {
      int x = queries[i];
      int st = 0;
      int end = n - 1;
      int count = 0;
 
      // Binary Searching the largest index
      while (st <= end)
      {
        int mid = (st + end) / 2;
        if (prefix.get(mid) >= x)
        {
          count = mid + 1;
          st = mid + 1;
        }
        else
        {
          end = mid - 1;
        }
      }
      answer.add(count);
    }
    return answer;
  }
 
  // Driver code
  public static void main(String args[])
  {
    int N = 4, Q = 2;
    int[] arr = {3, 7, 9, 16};
    int[] queries = {2, 1};
 
    // Function call
    ArrayList<Integer>ans = bitwiseAnd(N, Q, arr, queries);
    for (int i : ans)
      System.out.printf("%d ",i);
  }
}
 
// This code is contributed by aditya patil


Python3




# Python code to implement the approach
 
# Function to find the largest index
def bitwiseAnd (n, q, arr, queries):
    answer = []
    prefix = [0]*n
    prefix[0] = arr[0]
 
    # Constructing the prefix
    # bitwise and array.
    for i in range(1,n):
        prefix[i] = prefix[i - 1] & arr[i]
 
    for i in range(q):
        x = queries[i]
        st = 0
        end = n - 1
        count = 0
 
        # Binary Searching the largest index
        while (st <= end):
            mid = (st + end) // 2
            if (prefix[mid] >= x):
                count = mid + 1
                st = mid + 1
                 
            else:
                end = mid - 1
         
        answer.append(count)
             
    return answer
 
# Driver code
N,Q = 4,2
arr = [3, 7, 9, 16]
queries = [2, 1]
 
# Function call
ans = bitwiseAnd(N, Q, arr, queries)
for i in ans:
    print(i,end=" ")
 
# This code is contributed by shinjanpatra


C#




using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Driver Code
    static public void Main()
    {
 
        int N = 4, Q = 2;
        int[] arr = { 3, 7, 9, 16 };
        int[] queries = { 2, 1 };
 
        // Function call
        int[] ans = bitwiseAnd(N, Q, arr, queries);
        foreach(int i in ans) Console.Write(i + " ");
    }
 
    static int[] bitwiseAnd(int n, int q, int[] arr,
                            int[] queries)
    {
        List<int> answer = new List<int>();
        int[] prefix = new int[n];
        prefix[0] = arr[0];
 
        // Constructing the prefix
        // bitwise and array.
        for (int i = 1; i < n; i++) {
            prefix[i] = prefix[i - 1] & arr[i];
        }
 
        for (int i = 0; i < q; i++) {
            int x = queries[i];
            int st = 0;
            int end = n - 1;
            int count = 0;
 
            // Binary Searching the largest index
            while (st <= end) {
                int mid = (st + end) / 2;
                if (prefix[mid] >= x) {
                    count = mid + 1;
                    st = mid + 1;
                }
                else {
                    end = mid - 1;
                }
            }
            answer.Add(count);
        }
        return answer.ToArray();
    }
}
 
// This code is contributed by Ishan Khandelwal


Javascript




<script>
    // JavaScript code to implement the approach
 
    // Function to find the largest index
    const bitwiseAnd = (n, q, arr, queries) => {
        let answer = [];
        let prefix = new Array(n).fill(0);
        prefix[0] = arr[0];
 
        // Constructing the prefix
        // bitwise and array.
        for (let i = 1; i < n; i++) {
            prefix[i] = prefix[i - 1] & arr[i];
        }
 
        for (let i = 0; i < q; i++) {
            let x = queries[i];
            let st = 0;
            let end = n - 1;
            let count = 0;
 
            // Binary Searching the largest index
            while (st <= end) {
                let mid = parseInt((st + end) / 2);
                if (prefix[mid] >= x) {
                    count = mid + 1;
                    st = mid + 1;
                }
                else {
                    end = mid - 1;
                }
            }
            answer.push(count);
        }
        return answer;
    }
 
    // Driver code
    let N = 4, Q = 2;
    let arr = [3, 7, 9, 16];
    let queries = [2, 1];
 
    // Function call
    let ans = bitwiseAnd(N, Q, arr, queries);
    for (let i in ans)
        document.write(`${ans[i]} `);
 
    // This code is contributed by rakeshsahni
 
</script>


 
 

Output

2 3 

 

Time Complexity: O(N+ Q* log N)
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!