Longest Subarray With Maximum Bitwise AND (LeetCode 2419): Solution and Explanation
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
- Compute
target = max(nums). - Scan the array with a counter
runand the best lengthbest, both 0. - If
x == target, increaserunand updatebest = max(best, run). - Otherwise reset
runto 0, because the run of maximums is broken. - Return
best.
Step-by-step example
nums = [1,2,3,3,2,2]
- target = max(nums) = 3.
- nums[0] = 1 and nums[1] = 2 are below 3, so run stays 0.
- nums[2] = 3: run = 1, best = 1. nums[3] = 3: run = 2, best = 2.
- nums[4] = 2: 3 & 2 = 2 < 3, so the run breaks and run = 0. nums[5] = 2 keeps it at 0.
- 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 best1class Solution {
2 public int longestSubarray(int[] nums) {
3 int target = 0;
4 for (int x : nums) target = Math.max(target, x);
5 int best = 0, run = 0;
6 for (int x : nums) {
7 if (x == target) {
8 run++;
9 best = Math.max(best, run);
10 } else {
11 run = 0;
12 }
13 }
14 return best;
15 }
16}1class Solution {
2public:
3 int longestSubarray(vector<int>& nums) {
4 int target = *max_element(nums.begin(), nums.end());
5 int best = 0, run = 0;
6 for (int x : nums) {
7 if (x == target) {
8 run++;
9 best = max(best, run);
10 } else {
11 run = 0;
12 }
13 }
14 return best;
15 }
16};Time and space complexity
O(n)
One pass to find the maximum and one pass to measure runs.
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.