bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 581. Shortest Unsorted Continuous Subarray

581. Shortest Unsorted Continuous Subarray

Leetcode Solutions

Approach: Without Using Extra Space

  1. Initialize two pointers left and right to -1.
  2. Traverse the array from the start to find the first element that is greater than the next element, marking the start of the unsorted subarray. Store this index in left.
  3. If no such element is found, the array is already sorted, return 0.
  4. Traverse the array from the end to find the first element that is less than the previous element, marking the end of the unsorted subarray. Store this index in right.
  5. Find the minimum and maximum values in the subarray nums[left:right+1].
  6. Extend the left boundary to the left until the minimum value is greater than the array element at left - 1.
  7. Extend the right boundary to the right until the maximum value is less than the array element at right + 1.
  8. Return the length of the unsorted subarray, which is right - left + 1.
UML Thumbnail

Approach: Using Sorting

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...