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
Why Maximum Element = Maximum ANDBitwise AND Property: a & b ≤ min(a, b)7 (111)&5 (101)= 5 (101)6 (110)&3 (011)= 2 (010)Only identical maximum elements maintain maximum AND:9 (1001)&9 (1001)= 9 (1001) ✓💡 Key Insight:Maximum AND value = Maximum array element. Find longest consecutive sequence!
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

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra variables for maximum value and length tracking

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • The array contains at least one element
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen