Longest Subarray With Maximum Bitwise AND - Problem
You are given an integer array nums of size n. Your task is to find the longest contiguous subarray that has the maximum possible bitwise AND value.
Here's how it works:
- First, determine the maximum possible bitwise AND value among all possible subarrays
- Then, find the longest subarray that achieves this maximum AND value
Key insight: The bitwise AND operation can only preserve or reduce bits - it never increases them. This means the maximum AND value is simply the maximum element in the array!
Example: For array [1, 2, 3, 3, 2, 2], the maximum element is 3. The longest subarray with AND value 3 is [3, 3] with length 2.
Input & Output
example_1.py — Basic case
$
Input:
nums = [1, 2, 3, 3, 2, 2]
›
Output:
2
💡 Note:
The maximum AND value is 3 (the maximum element). The longest subarray with AND value 3 is [3, 3] with length 2.
example_2.py — Single element
$
Input:
nums = [1, 2, 3, 4]
›
Output:
1
💡 Note:
The maximum AND value is 4. There's only one element with value 4, so the longest subarray length is 1.
example_3.py — All same elements
$
Input:
nums = [5, 5, 5, 5]
›
Output:
4
💡 Note:
All elements are the same (5), so the entire array has AND value 5, giving us length 4.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Maximum
Find the maximum element - this is our target AND value
2
Find Streaks
Locate all consecutive sequences of this maximum element
3
Return Longest
The longest streak gives us our answer
Key Takeaway
🎯 Key Insight: The maximum possible bitwise AND value in any subarray equals the maximum element in the entire array, since AND operations can only maintain or reduce values, never increase them.
Time & Space Complexity
Time Complexity
O(n)
Two passes through array: O(n) to find maximum + O(n) to find longest sequence
✓ Linear Growth
Space Complexity
O(1)
Only using constant extra variables for maximum value and length tracking
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
- The array contains at least one element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code