Skip to main content
Back to problems
#2419
Medium Algorithms

Longest subarray with maximum bitwise and

Array Bit Manipulation Brainteaser
65.4% acceptance
Feb 25, 2026
1316
110
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_subarray(nums: Vec<i32>) -> i32 {
    // The max bitwise AND of any subarray equals the maximum element.
    // AND can only decrease, so a single max element achieves the maximum.
    // We need the longest consecutive run of the maximum element.
    let max_val = *nums.iter().max().unwrap();
    let mut ans = 0;
    let mut len = 0;
    for &n in &nums {
      if n == max_val {
        len += 1;
        ans = ans.max(len);
      } else {
        len = 0;
      }
    }
    ans
  }
}