Longest Subarray With Maximum Bitwise AND (LeetCode 2419): Solution and Explanation

Medium
Array
Bit Manipulation
Brainteaser

Among all subarrays of nums, some reach the largest possible bitwise AND. Return the length of the longest such subarray.

Intuition

Trying every subarray and computing its AND is O(n^2), far too slow for 100,000 elements. The way out is to ask what the largest AND can even be.

AND can only clear bits. A bit of a & b is 1 only when it is 1 in both, so a & b is never larger than a or b. Extending a subarray adds another operand, so its AND stays the same or drops. The largest AND of any subarray is therefore the largest single element, max(nums).

Now which subarrays reach that value? If a subarray contains a number other than the maximum, that number is smaller, so it lacks at least one 1 bit of the maximum, and ANDing it in clears that bit. Only runs made entirely of the maximum keep AND equal to it. The answer is simply the longest run of consecutive copies of max(nums).

Approach: Longest run of the maximum

  1. Compute target = max(nums).
  2. Scan the array with a counter run and the best length best, both 0.
  3. If x == target, increase run and update best = max(best, run).
  4. Otherwise reset run to 0, because the run of maximums is broken.
  5. Return best.

Step-by-step example

nums = [1,2,3,3,2,2]
  1. target = max(nums) = 3.
  2. nums[0] = 1 and nums[1] = 2 are below 3, so run stays 0.
  3. nums[2] = 3: run = 1, best = 1. nums[3] = 3: run = 2, best = 2.
  4. nums[4] = 2: 3 & 2 = 2 < 3, so the run breaks and run = 0. nums[5] = 2 keeps it at 0.
  5. The longest run of 3s is indices 2..3, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def longestSubarray(self, nums: List[int]) -> int:
3        target = max(nums)
4        best = run = 0
5        for x in nums:
6            if x == target:
7                run += 1
8                best = max(best, run)
9            else:
10                run = 0
11        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass to find the maximum and one pass to measure runs.

Space

O(1)

Only the target and two counters are stored.

Other approaches

Single pass with a running maximum (time O(n), space O(1))

Track the maximum while scanning. When a strictly larger value appears, reset both best and run because older runs no longer count. It gives the same answer in one pass.

Brute force over all subarrays (time O(n^2), space O(1))

Compute the AND of every subarray incrementally and track the longest one equal to the best value. Correct but quadratic.

Common mistakes

  • Thinking a longer subarray could have a larger AND. AND never sets bits, so the best AND is always the single largest element.
  • Counting all copies of the maximum instead of the longest consecutive run. Copies separated by a smaller value cannot be in the same subarray.
  • Forgetting to update best inside the run, then missing a run that reaches the end of the array.

Frequently asked questions

Why is the maximum AND equal to max(nums)?

Any subarray's AND is at most each of its elements, so it is at most the largest element in it, which is at most max(nums). The one-element subarray [max(nums)] reaches that bound.

Could two different numbers AND to the maximum?

No. If x is not the maximum it is smaller, so it is missing some 1 bit of the maximum, and max & x clears that bit.

Is this really a bit manipulation problem?

The bit fact is the whole insight: once you see that AND only removes bits, the solution is a simple counting scan.