Longest Subarray With Maximum Bitwise AND - Problem

You are given an integer array nums of size n.

Consider a non-empty subarray from nums that has the maximum possible bitwise AND.

  • In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.

Return the length of the longest such subarray.

The bitwise AND of an array is the bitwise AND of all the numbers in it.

A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,3,2,1]
Output: 2
💡 Note: The maximum bitwise AND is 3 (from element 3). The longest subarray with AND equal to 3 is [3,3] with length 2.
Example 2 — Single Element
$ Input: nums = [1,2,3,4]
Output: 1
💡 Note: Maximum element is 4. The longest subarray with maximum AND is [4] with length 1.
Example 3 — All Same Elements
$ Input: nums = [5,5,5,5]
Output: 4
💡 Note: All elements are 5, so the entire array has AND value 5. Length is 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Longest Subarray With Maximum Bitwise ANDInput: [1,2,3,3,2,1]123321Maximum element: 3Maximum possible AND: 3 (achieved by subarray containing only 3s)Longest sequenceAny subarray: [3] → AND = 3, [3,3] → AND = 3Mixed subarray: [2,3] → AND = 2, [3,2] → AND = 2Output: 2 (length of [3,3])
Understanding the Visualization
1
Input Array
Given array with various integer elements
2
Key Insight
Maximum AND equals maximum element value
3
Find Sequence
Locate longest consecutive sequence of max element
Key Takeaway
🎯 Key Insight: Maximum bitwise AND of any subarray equals the maximum array element - find longest consecutive sequence of max element
Asked in
Apple 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
856 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