LeetCode 2401: Longest Nice Subarray Solution

Master LeetCode problem 2401 (Longest Nice Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2401. Longest Nice Subarray

Problem Explanation

Explanation

To find the longest nice subarray, we can iterate through the given array and check for each possible subarray whether it is a nice subarray or not. We can use a nested loop to consider all subarrays starting from each index in the array. For each subarray, we check if the bitwise AND of every pair of elements at different positions is equal to 0. If it is, we update the maximum length of the nice subarray found so far.

Algorithm

  1. Initialize a variable maxLen to store the maximum length of the nice subarray found so far.
  2. Iterate over the array using two nested loops to consider all possible subarrays.
  3. For each subarray, check if the bitwise AND of every pair of elements at different positions is equal to 0.
  4. If the subarray is nice, update maxLen if the current subarray length is greater.
  5. Return maxLen as the result.

Time Complexity

The time complexity of this approach is O(n^2), where n is the length of the input array.

Space Complexity

The space complexity is O(1) as we are not using any extra space other than a few variables.

Solution Code

class Solution {
    public int longestNiceSubarray(int[] nums) {
        int maxLen = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                if (isNiceSubarray(nums, i, j)) {
                    maxLen = Math.max(maxLen, j - i + 1);
                }
            }
        }
        return maxLen;
    }
    
    private boolean isNiceSubarray(int[] nums, int start, int end) {
        for (int i = start; i <= end; i++) {
            for (int j = start; j <= end; j++) {
                if (i != j && (nums[i] & nums[j]) != 0) {
                    return false;
                }
            }
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2401 (Longest Nice Subarray)?

This page provides optimized solutions for LeetCode problem 2401 (Longest Nice Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2401 (Longest Nice Subarray)?

The time complexity for LeetCode 2401 (Longest Nice Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2401 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2401 in Java, C++, or Python.

Back to LeetCode Solutions