Problem
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.
A subarray is a contiguous part of an array.
Note that subarrays of length 1 are always considered nice.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Method 1 - Using Sliding Window
To solve the problem, we aim to find the longest subarray (contiguous sequence) of numbers such that the bitwise AND of any two numbers in different positions of the subarray is 0. This involves ensuring that no two numbers in the subarray have overlapping 1s in their binary representation.
Approach
- Use a sliding window technique to maintain the longest possible nice subarray.
- Keep a variable
currMaskthat represents the cumulative bitwise OR of the elements in the current window (ltor). - As we expand the window by moving the right pointer
r, check whether adding the elementnums[r]violates the “nice” condition (i.e., whether(currMask & nums[r]) != 0). - If the condition is violated, shrink the window by incrementing the left pointer
land adjustingcurrMask. - Maintain and update the maximum length of the nice subarray (
ans) along the way.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the array. The sliding window ensures that each element is processed at most twice (once when expanding the window, and once when contracting it). Hence the overall time isO(n). - 🧺 Space complexity:
O(1)as only a few variables are used.