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
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
✓ Linear Growth
Space Complexity
O(1)
Only using constant extra space for pointers and OR value
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- All elements are positive integers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code