Longest Subarray With Maximum Bitwise AND

The maximum AND equals the array's max — find the longest consecutive run of that value.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
bit-manipulation array

Problem#

Return the length of the longest subarray whose bitwise AND equals the maximum bitwise AND achievable over any subarray of nums.

Examples#

  • [1,2,3,3,2,2]2 (the two consecutive 3s).
  • [1,2,3,4]1.

Constraints#

  • 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^6.

Approach#

ANDing with any value < max strictly reduces the result, so the optimal AND equals the array maximum. The answer is the longest streak of consecutive elements equal to that max.

Solution#

Longest Subarray With Maximum Bitwise AND
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int mx = *max_element(nums.begin(), nums.end());
int ans = 0, run = 0;
for (int v : nums) {
if (v == mx) ans = max(ans, ++run);
else run = 0;
}
return ans;
}
};

Editorial#

The key observation: AND is monotonic — adding more values to the AND can only clear bits, never set them. So the largest achievable AND is the largest single element, and to “achieve” it across a subarray, every value must equal it.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.