Longest Subarray With Maximum Bitwise AND

You are given an integer array `nums`. Let `k` be the largest bitwise AND over all non-empty subarrays of `nums`. Return the length of the longest subarray whose bitwise AND equals `k`. The bitwise AND of a subarray is the AND of all of its elements. A subarray is a contiguous run of elements.

30:00

Longest Subarray With Maximum Bitwise AND
medium
Free written solution
Topics
Companies

You are given an integer array nums. Let k be the largest bitwise AND over all non-empty subarrays of nums. Return the length of the longest subarray whose bitwise AND equals k.

The bitwise AND of a subarray is the AND of all of its elements. A subarray is a contiguous run of elements.

Example 1:
Input: {"nums":[1,2,3,3,2,2]}
Output: 2
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1061 \leq \text{nums[i]} \leq 10^6

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,3,2,2]}

Key fact: a & b never has a 1 bit that a lacks, so ANDing in more elements can only keep or lower the value. No subarray can beat its largest element.

nums

target = ?

1

0

2

1

3

2

3

3

2

4

2

5

amber = equals max · green fill = current run · green bar = best run

run = 0
best = 0
Variables
VariableValue
n6
DepthFunction Call
Stack empty
0/11