## Similar Problems

Similar Problems not available

# Longest Subarray With Maximum Bitwise And - Leetcode Solution

## Companies:

LeetCode: Longest Subarray With Maximum Bitwise And Leetcode Solution

Difficulty: Medium

Topics: bit-manipulation array

Problem Statement:

Given an integer array nums, find the maximum length of a subarray where the bitwise AND of all its elements is equal to zero.

Example:

Input: nums = [2,2,2,2,5,6,7,8] Output: 0

Input: nums = [1,2,4,8] Output: 1 Explanation: The maximum length subarray is [2].

Solution:

The problem is asking to find the longest subarray with maximum bitwise AND value of 0. The bitwise AND operation is used to compare the corresponding bits of the operands and returns a 1 in the result for every pair of bits that are both 1. So, bitwise AND of a binary number with 0 results in 0. Thus, we need to find a subarray whose bitwise AND with all the elements is 0.

One approach to solving the problem is to use a brute force algorithm that checks all possible subarrays and finds the longest subarray with maximum bitwise AND value of 0. However, the time complexity of the brute force algorithm is O(n^3) which is not efficient for large inputs.

Another approach is to observe that if there are any two elements in the array with their most significant bit (MSB) different, their bitwise AND would result in 0. So, we need to find pairs of elements in the array whose most significant bit (MSB) is different and whose bitwise AND is zero. Once we find such pairs, we add their lengths to get the total length of the subarray.

To implement the above approach, we can use a hash map to store the index of the first occurrence of each unique MSB in the array. We then iterate over the array to find the pairs of elements whose MSBs are different and their bitwise AND is 0. We calculate the length of each subarray and store the length of the longest subarray. Finally, we return the length of the longest subarray.

Python Code:

class Solution: def maxAnd(self, nums: List[int]) -> int: # create a hash map to store the index of the first occurrence of each unique MSB in the array msb_index = {} for i in range(len(nums)): msb = 1 << (len(bin(nums[i])) - 3) if msb not in msb_index: msb_index[msb] = i

```
# iterate over the array to find pairs of elements whose MSBs are different and their bitwise AND is 0
longest_subarray = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] & nums[j] == 0:
msb1 = 1 << (len(bin(nums[i])) - 3)
msb2 = 1 << (len(bin(nums[j])) - 3)
if msb1 != msb2:
length = j - i + 1
longest_subarray = max(longest_subarray, length)
return longest_subarray
```

Time Complexity: O(n^2) Space Complexity: O(n)

## Longest Subarray With Maximum Bitwise And Solution Code

`1`