LeetCode 0581. Shortest Unsorted Continuous Subarray Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0581. Shortest Unsorted Continuous Subarray

Description

Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.

Return the shortest such subarray and output its length.

 

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 104
  • -105 <= nums[i] <= 105

 

Follow up: Can you solve it in O(n) time complexity?

Solutions

Solution 1: Sorting

We can first sort the array, and then compare the sorted array with the original array to find the leftmost and rightmost positions where they differ. The length between them is the length of the shortest unsorted continuous subarray.

The time complexity is O(n × log n), and the space complexity is O(n). Here, n is the length of the array.

PythonJavaC++GoTypeScriptRust
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: arr = sorted(nums) l, r = 0, len(nums) - 1 while l <= r and nums[l] == arr[l]: l += 1 while l <= r and nums[r] == arr[r]: r -= 1 return r - l + 1(code-box)

Solution 2: Maintaining the Maximum Value on the Left and the Minimum Value on the Right

We can traverse the array from left to right and maintain a maximum value mx. If the current value is less than mx, it means that the current value is not in the correct position, and we update the right boundary r to the current position. Similarly, we can traverse the array from right to left and maintain a minimum value mi. If the current value is greater than mi, it means that the current value is not in the correct position, and we update the left boundary l to the current position. At initialization, we set l and r to -1. If l and r are not updated, it means that the array is already sorted, and we return 0. Otherwise, we return r - l + 1.

The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the array.

PythonJavaC++GoTypeScriptRust
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: mi, mx = inf, -inf l = r = -1 n = len(nums) for i, x in enumerate(nums): if mx > x: r = i else: mx = x if mi < nums[n - i - 1]: l = n - i - 1 else: mi = nums[n - i - 1] return 0 if r == -1 else r - l + 1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !