Find largest index till which Bitwise AND of elements is at least X for Q queries
Last Updated :
23 Jul, 2025
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>
Time Complexity: O(N * Q)
Auxiliary Space: O(Q)
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>
Time Complexity: O(N+ Q* log N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem