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

• Difficulty Level : Hard
• Last Updated : 23 Jun, 2022

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 & arr &. . .& 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[ ] = 
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.
• If arr 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.

Below is the implementation of the above approach :

## C++

 `// C++ code to implement the approach`   `#include ` `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;` `        ``if` `(arr < 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 bitwiseAnd(``int` `n,``int` `q,``int``[] arr,``int``[] queries)` `{` `    ``ArrayList answer = ``new` `ArrayList();` `    ``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` `    ``ArrayListans = 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;` `      ``if` `(arr < 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

 ``

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 with arr.
• 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.

Below is the implementation of the above approach.

## C++

 `// C++ code to implement the approach`   `#include ` `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 = arr;`   `    ``// 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 bitwiseAnd(``int` `n,``int` `q,``int``[] arr,``int``[] queries)` `  ``{` `    ``ArrayList answer = ``new` `ArrayList();` `    ``ArrayList prefix = ``new` `ArrayList();` `    ``for``(``int` `i=``0``;i= 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` `    ``ArrayListans = 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 = arr;`   `        ``// 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

 ``

Output

`2 3 `

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :