#2401

Longest Nice Subarray

Medium
ArrayBit ManipulationSliding WindowSliding WindowBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a sliding window approach to efficiently find the longest nice subarray. By maintaining a window of elements and checking their bitwise AND, we can dynamically adjust the window size without rechecking all pairs.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers (left and right) to represent the current window.
  2. 2Step 2: Use a variable to keep track of the bitwise AND of the current window.
  3. 3Step 3: Expand the right pointer to include new elements in the window, updating the AND.
  4. 4Step 4: If the AND becomes non-zero, move the left pointer to shrink the window until the AND is zero again.
  5. 5Step 5: Keep track of the maximum length of the window when it is nice.
solution.py14 lines
1# Full working Python code
2
3def longestNiceSubarray(nums):
4    max_length = 1
5    left = 0
6    current_and = 0
7    for right in range(len(nums)):
8        current_and &= nums[right]
9        while current_and != 0:
10            current_and &= ~nums[left]
11            left += 1
12        max_length = max(max_length, right - left + 1)
13    return max_length
14

Complexity note: The time complexity is O(n) because we traverse the array with two pointers, and each element is processed at most twice (once when added and once when removed from the window).

  • 1The maximum length of a nice subarray cannot exceed 30 due to the bitwise nature of the problem.
  • 2Using bitwise operations efficiently can significantly reduce the number of checks needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.