708851. Bitwise AND of the Array
Bitwise AND of the Array
Summary
Given an array arr, find the maximum bitwise AND value that can be obtained by performing bitwise AND operation on all elements in the array. The goal is to maximize the result.
The problem requires a good understanding of bitwise operations and the ability to analyze the problem at a high level.
Detailed Explanation
To solve this problem, we need to understand how bitwise AND operation works. When two numbers are performed bitwise AND operation, it compares each bit of the first operand (number) to the corresponding bit in the second operand (number). If both bits are 1, then the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Now let's analyze the problem at a high level. We want to maximize the bitwise AND value that can be obtained by performing bitwise AND operation on all elements in the array. This means we need to find the maximum number of bits that are 1 in the binary representation of the numbers in the array, and then set these bits to 1 in the result.
Here's a step-by-step breakdown of the solution:
- Find the maximum value
max_valin the array. - Convert
max_valto binary using bitwise operators (e.g.,max_val & ((1 << k) - 1)). - For each bit position
k, check if all numbers in the array have a 1 at that position. If they do, set the result bit to 1. - Return the maximum bitwise AND value.
The time complexity of this solution is O(n), where n is the size of the input array, as we need to iterate over the array once to find the maximum value and then again to perform the bitwise AND operation. The space complexity is O(1), as we only use a constant amount of space to store the result.
Optimized Solutions
Java
public int findMaximumBitwiseAND(int[] arr) {
int max_val = Arrays.stream(arr).max().getAsInt();
int result = 0;
for (int k = 0; k < 32; k++) {
if (IntStream.range(0, arr.length)
.allMatch(i -> ((arr[i] >> k) & 1) == 1)) {
result |= (1 << k);
}
}
return result;
}