LeetCode 2401: Longest Nice Subarray
LeetCode 2401 Solution 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
- Initialize a variable
maxLen
to store the maximum length of the nice subarray found so far. - Iterate over the array using two nested loops to consider all possible subarrays.
- For each subarray, check if the bitwise AND of every pair of elements at different positions is equal to 0.
- If the subarray is nice, update
maxLen
if the current subarray length is greater. - 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.
LeetCode 2401 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 2401
Improve Your LeetCode 2401 Solution
Use the editor below to refine the provided solution for LeetCode 2401. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...