Longest Nice Subarray - 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.

Note: A subarray is a contiguous part of an array. Subarrays of length 1 are always considered nice.

Example: In array [1, 3, 8, 48, 10], the subarray [1, 8, 48] is nice because:
1 & 8 = 0
1 & 48 = 0
8 & 48 = 0

Input & Output

example_1.py — Basic Case
$ Input: [1,3,8,48,10]
Output: 3
💡 Note: The longest nice subarray is [1,8,48] with length 3. All pairs have AND = 0: 1&8=0, 1&48=0, 8&48=0.
example_2.py — Powers of 2
$ Input: [1,2,4,8,16]
Output: 5
💡 Note: All elements are powers of 2, so no two elements share any bit positions. The entire array forms a nice subarray.
example_3.py — Single Element
$ Input: [5]
Output: 1
💡 Note: A single element array always forms a nice subarray of length 1.

Visualization

Tap to expand
🏨 Binary Light Switch HotelFloor 1: Compatible Guests1Switches: 18Switches: 848Switches: 32,16✅ No Conflicts!Floor 2: Conflict Detected1Switches: 13Switches: 1,2❌ Both need switch 1!Solution Strategy: Sliding Window1. Keep OR of current floor switches2. For new guest, check if ANY current switch conflicts (AND ≠ 0)3. If conflict, remove guests from left until resolved🎯 Maximum floor capacity = 3 guests
Understanding the Visualization
1
Guest Check-in
Each guest arrives with their unique set of required light switches (bits)
2
Floor Assignment
Try to assign guest to current floor if no switch conflicts exist
3
Conflict Resolution
If conflicts arise, remove guests from the left until resolved
4
Optimal Floor
Track the maximum number of compatible guests on any floor
Key Takeaway
🎯 Key Insight: Use bitwise OR to track all occupied switches, and XOR to efficiently remove guests when shrinking the window.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Each element is added once and removed at most once

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra space for pointers and OR value

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • All elements are positive integers
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 18
28.5K Views
Medium Frequency
~22 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen