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.

A subarray is a contiguous part of an array.

Note: subarrays of length 1 are always considered nice.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,8,48,10]
Output: 3
💡 Note: The longest nice subarray is [3,8,48] with length 3. Each pair has AND = 0: 3&8=0, 3&48=0, 8&48=0.
Example 2 — Single Element
$ Input: nums = [3,1,5,11,13]
Output: 1
💡 Note: No pair of elements has AND = 0, so the longest nice subarray has length 1 (any single element).
Example 3 — All Elements Nice
$ Input: nums = [1,2,4]
Output: 3
💡 Note: All elements have disjoint bits: 1&2=0, 1&4=0, 2&4=0. The entire array is nice with length 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Longest Nice Subarray INPUT nums array: 1 3 8 48 10 i=0 i=1 i=2 i=3 i=4 Binary Representation: 1 = 000001 3 = 000011 8 = 001000 48 = 110000 10 = 001010 Nice Subarray: Bitwise AND of every pair of elements = 0 (No overlapping bits) ALGORITHM STEPS 1 Sliding Window Use two pointers left, right 2 Track Used Bits OR all elements in window 3 Check Conflict If (usedBits AND new) != 0 4 Shrink Window Move left, XOR to remove Window Check Example: [3, 8, 48]: 3 AND 8 = 0 OK 3 AND 48 = 0 OK 8 AND 48 = 0 OK usedBits = 3|8|48 = 59 111011 (no overlap) FINAL RESULT Longest Nice Subarray 3 Nice Subarray Found: 1 3 8 48 [3, 8, 48] at indices 1-3 Why [3,8,48] is Nice: 3 = 00 0011 8 = 00 1000 48 = 11 0000 No bit position shared! All pairs AND = 0 OK Key Insight: A subarray is "nice" when no two numbers share any bit position. We track used bits with OR operation. If (usedBits AND nums[right]) != 0, there's a conflict -- shrink window from left using XOR to remove bits. TutorialsPoint - Longest Nice Subarray | Optimal Solution (Sliding Window + Bit Manipulation)
Asked in
Google 25 Amazon 20 Microsoft 15
18.5K Views
Medium Frequency
~25 min Avg. Time
850 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