Longest Nice Subarray (LeetCode 2401): Solution and Explanation
Find the longest contiguous subarray in which every pair of elements has a bitwise AND of 0, meaning no two elements share a set bit.
Intuition
Two numbers AND to 0 exactly when they have no set bit in common. So a nice subarray is one where every bit position is owned by at most one element.
That means the OR of a nice window is a perfect record of which bits are taken. Call it used. A new number fits if and only if used & x == 0.
If it does not fit, the only way to make room is to drop elements from the left end. Because bits in the window are disjoint, removing an element is just used ^= nums[left], which clears exactly its bits.
Approach: Sliding window with an OR mask
- Start with
used = 0,left = 0,best = 0. - For each
right, letx = nums[right]. - While
used & xis not 0, remove the left element withused ^= nums[left]and moveleftforward. - Add the new element with
used |= x. - Update
bestwith the window lengthright - left + 1, and return it at the end.
Step-by-step example
nums = [1,3,8,48,10]
- right = 0: 1 (bit 0) joins an empty window. used = 1, best = 1.
- right = 1: 3 (bits 0, 1) clashes on bit 0. Drop 1, used = 0, then add 3: used = 3, window [1..1].
- right = 2: 8 (bit 3) fits. used = 11, window [1..2], best = 2.
- right = 3: 48 (bits 4, 5) fits. used = 59, window [1..3], best = 3.
- right = 4: 10 (bits 1, 3) clashes. Drop 3 (used = 56), still clashes on bit 3, drop 8 (used = 48). Add 10: window [3..4], length 2. The answer stays 3.
Code: Python, Java, C++
1class Solution:
2 def longestNiceSubarray(self, nums: List[int]) -> int:
3 used = 0
4 left = 0
5 best = 0
6 for right, x in enumerate(nums):
7 while used & x:
8 used ^= nums[left]
9 left += 1
10 used |= x
11 best = max(best, right - left + 1)
12 return best1class Solution {
2 public int longestNiceSubarray(int[] nums) {
3 int used = 0;
4 int left = 0;
5 int best = 0;
6 for (int right = 0; right < nums.length; right++) {
7 while ((used & nums[right]) != 0) {
8 used ^= nums[left];
9 left++;
10 }
11 used |= nums[right];
12 best = Math.max(best, right - left + 1);
13 }
14 return best;
15 }
16}1class Solution {
2public:
3 int longestNiceSubarray(vector<int>& nums) {
4 int used = 0;
5 int left = 0;
6 int best = 0;
7 for (int right = 0; right < (int)nums.size(); right++) {
8 while ((used & nums[right]) != 0) {
9 used ^= nums[left];
10 left++;
11 }
12 used |= nums[right];
13 best = max(best, right - left + 1);
14 }
15 return best;
16 }
17};Time and space complexity
O(n)
Each index enters the window once and leaves it at most once, and each step is a constant number of bit operations.
O(1)
Only the mask and a few indices are stored.
Other approaches
Check every start with early stop (time O(30 * n), space O(1))
For each start index, extend to the right while the running OR has no overlap with the next number. A nice window has at most 30 elements because each owns a distinct bit, so each start does at most 30 steps.
Brute force pairs (time O(n^3), space O(1))
Test every subarray by ANDing all pairs. Correct but far too slow for n up to 10^5.
Common mistakes
- Removing the left element with subtraction or AND-NOT works too, but XOR is only safe because the window's bits are disjoint. Do not apply the XOR trick to a window that may share bits.
- Using
ifinstead ofwhilewhen shrinking. One removal may not clear every clashing bit, as in the walkthrough where both 3 and 8 must go. - Checking only neighboring pairs. The condition is about every pair in the window, so 1 and 5 three positions apart still clash.
- Forgetting that a single element is always nice, so the answer is at least 1 for a non-empty array.
Frequently asked questions
Why is the OR enough to test a new element?
The new element must not share a bit with any member of the window. The OR has a bit set exactly when some member has it, so used & x == 0 checks all members at once.
Why can XOR remove the left element?
In a nice window each set bit belongs to exactly one element. XOR with that element flips its bits from 1 to 0 and leaves every other bit alone.
How long can a nice subarray be?
At most 30, because values are below 2^30 and each positive element needs at least one bit nobody else in the window uses.