#2419
Longest Subarray With Maximum Bitwise AND
MediumArrayBit ManipulationBrainteaserHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that the maximum bitwise AND can only be formed by contiguous elements that are equal to the maximum value in the array. Thus, we can simply find the maximum number and count its longest contiguous occurrence.
⚙️
Algorithm
2 steps- 1Step 1: Find the maximum value in the array.
- 2Step 2: Iterate through the array to count the length of the longest contiguous subarray of this maximum value.
solution.py14 lines
1def longest_subarray_with_max_bitwise_and(nums):
2 max_value = max(nums)
3 max_length = 0
4 current_length = 0
5 for num in nums:
6 if num == max_value:
7 current_length += 1
8 max_length = max(max_length, current_length)
9 else:
10 current_length = 0
11 return max_length
12
13# Example usage
14print(longest_subarray_with_max_bitwise_and([1, 2, 3, 3, 2, 2]))ℹ
Complexity note: This complexity is achieved because we only traverse the array twice: once to find the maximum and once to count the longest contiguous segment.
- 1The maximum bitwise AND of a subarray can only be achieved by using elements that are equal to the maximum element in the array.
- 2Contiguous segments of the maximum value determine the length of the longest subarray.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.