#2401
Medium Algorithms Longest nice subarray
Array Bit Manipulation Sliding Window
64.8% acceptance
Feb 25, 2026
2082
62
You are given an array nums consisting of positive integers.
We call a subarray of nums nice if the bitwise AND of every pair of elements
that are in different positions in the subarray is equal to 0.
Return the length of the longest nice subarray.
Note that subarrays of length 1 are always considered nice.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn longest_nice_subarray(nums: Vec<i32>) -> i32 {
let mut used = 0i32;
let mut left = 0;
let mut ans = 0;
for right in 0..nums.len() {
while used & nums[right] != 0 {
used ^= nums[left];
left += 1;
}
used |= nums[right];
ans = ans.max(right - left + 1);
}
ans as i32
}
}