Practice › Bit Manipulation
Maximum AND of a Pair
Medium · Bit Manipulation · Asked at Amazon, Microsoft, Codenation
Print the maximum value of a[i] & a[j] (bitwise AND) over all pairs i < j.
Input
First line: n. Second line: n space-separated integers.
Output
The maximum AND of any pair.
Constraints
- 2 ≤ n ≤ 10^5
- 0 ≤ a[i] < 2^30
Build the answer bit by bit from the top. Try to set bit b on top of the bits already chosen: if at least two numbers contain all of those bits, keep it. 30 passes over the array — O(30 × n).
Example 1
Input
4 4 8 12 16
Output
8
Example 2
Input
4 4 8 16 2
Output
0
Hints
- Checking all pairs is O(n²) — too slow for 10^5.
- A higher bit is worth more than all lower bits together, so decide the bits from the top.
- Bit b can be in the answer only if two numbers have it together with all the bits already chosen.
Approach
Let ans = 0. For b from 29 down to 0, form want = ans | (1 << b) and count how many numbers x satisfy (x & want) == want. If at least two do, some pair's AND contains all of want, so keep the bit: ans = want. Otherwise the bit cannot be set without losing a higher one, so skip it. This greedy is correct because bit b outweighs bits 0…b−1 combined.
Complexity: O(30 · n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (auto &x : a) cin >> x;
int ans = 0;
for (int b = 29; b >= 0; b--) {
int want = ans | (1 << b), count = 0;
for (int x : a)
if ((x & want) == want && ++count >= 2) break;
if (count >= 2) ans = want;
}
cout << ans << "\n";
return 0;
}Python solution
import sys
data = sys.stdin.buffer.read().split()
n = int(data[0])
a = list(map(int, data[1 : 1 + n]))
ans = 0
for b in range(29, -1, -1):
want = ans | (1 << b)
keep = [x for x in a if x & want == want]
if len(keep) >= 2:
ans = want
a = keep # only these numbers can still form the best pair
print(ans)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (int) in.nval;
}
int ans = 0;
for (int b = 29; b >= 0; b--) {
int want = ans | (1 << b), count = 0;
for (int x : a)
if ((x & want) == want && ++count >= 2) break;
if (count >= 2) ans = want;
}
System.out.println(ans);
}
}