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 AND INPUT nums array: 1 i=0 2 i=1 3 i=2 3 i=3 2 i=4 1 i=5 Bitwise AND property: a AND b <= min(a, b) Example AND operations: 3 AND 3 = 3 (max!) 2 AND 3 = 2 1 AND 2 = 0 Goal: Find longest subarray with AND = max value n = 6 ALGORITHM STEPS (Two Pass Solution) 1 Pass 1: Find Maximum Scan array to find max value maxVal = max(nums) = 3 2 Key Observation AND of subarray = maxVal only when ALL elements = maxVal 3 Pass 2: Count Consecutive Find longest streak of maxVal 1 2 3 3 2 1 streak=2 4 Track Maximum Length Update result with max streak result = max(result, streak) FINAL RESULT Longest subarray with max AND: 1 2 3 3 2 1 Subarray [3, 3] Output: 2 Verification: maxVal = 3 AND(3,3) = 3 = maxVal Length = 2 ... OK Key Insight: The bitwise AND of any subarray is always <= the minimum element in that subarray. Therefore, the maximum AND equals the maximum element in the array, and it can only be achieved by a subarray containing ONLY that maximum element. Solution: Find longest consecutive run of max values. Complexity Time: O(n) | Space: O(1) TutorialsPoint - Longest Subarray With Maximum Bitwise AND | Optimized Two Pass Solution
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