2401. Longest Nice Subarray LeetCode Solution
In this guide, you will get 2401. Longest Nice Subarray LeetCode Solution with the best time and space complexity. The solution to Longest Nice Subarray problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Longest Nice Subarray solution in C++
- Longest Nice Subarray solution in Java
- Longest Nice Subarray solution in Python
- Additional Resources

Problem Statement of Longest Nice Subarray
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 that subarrays of length 1 are always considered nice.
Example 1:
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
– 3 AND 8 = 0.
– 3 AND 48 = 0.
– 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
Example 2:
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2401. Longest Nice Subarray LeetCode Solution in C++
class Solution {
public:
int longestNiceSubarray(vector<int>& nums) {
int ans = 0;
int used = 0;
for (int l = 0, r = 0; r < nums.size(); ++r) {
while (used & nums[r])
used ^= nums[l++];
used |= nums[r];
ans = max(ans, r - l + 1);
}
return ans;
}
};
/* code provided by PROGIEZ */
2401. Longest Nice Subarray LeetCode Solution in Java
class Solution {
public int longestNiceSubarray(int[] nums) {
int ans = 0;
int used = 0;
for (int l = 0, r = 0; r < nums.length; ++r) {
while ((used & nums[r]) > 0)
used ^= nums[l++];
used |= nums[r];
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
// code provided by PROGIEZ
2401. Longest Nice Subarray LeetCode Solution in Python
class Solution:
def longestNiceSubarray(self, nums: list[int]) -> int:
ans = 0
used = 0
l = 0
for r, num in enumerate(nums):
while used & num:
used ^= nums[l]
l += 1
used |= num
ans = max(ans, r - l + 1)
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.