Leetcode Problem 2401. Longest Nice Subarray

2401. Longest Nice Subarray

Leetcode Solutions

Sliding Window with Bitwise Operations

  1. Initialize two pointers left and right to 0, which will represent the window's boundaries.
  2. Initialize a variable current_and to 0, which will store the cumulative AND of the current window.
  3. Initialize a variable max_length to 1, which will store the maximum length of a nice subarray found so far.
  4. Iterate with right over the elements of nums. a. For each element, perform a bitwise AND with current_and. b. If the result is non-zero, it means there is a conflict, and we need to shrink the window from the left. c. While there is a conflict, use XOR to remove the leftmost element's bits from current_and and increment left.
  5. After resolving conflicts (if any), update current_and by performing a bitwise OR with the current element.
  6. Update max_length with the maximum of its current value and the size of the current window (right - left + 1).
  7. Return max_length as the result.
UML Thumbnail

Brute Force with Bitwise Checking

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...