Longest Nice Subarray (LeetCode 2401): Solution and Explanation

Medium
Array
Bit Manipulation
Sliding Window

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

  1. Start with used = 0, left = 0, best = 0.
  2. For each right, let x = nums[right].
  3. While used & x is not 0, remove the left element with used ^= nums[left] and move left forward.
  4. Add the new element with used |= x.
  5. Update best with the window length right - left + 1, and return it at the end.

Step-by-step example

nums = [1,3,8,48,10]
  1. right = 0: 1 (bit 0) joins an empty window. used = 1, best = 1.
  2. right = 1: 3 (bits 0, 1) clashes on bit 0. Drop 1, used = 0, then add 3: used = 3, window [1..1].
  3. right = 2: 8 (bit 3) fits. used = 11, window [1..2], best = 2.
  4. right = 3: 48 (bits 4, 5) fits. used = 59, window [1..3], best = 3.
  5. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index enters the window once and leaves it at most once, and each step is a constant number of bit operations.

Space

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 if instead of while when 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.