diff --git a/0581_shortest-unsorted-continuous-subarray/README.md b/0581_shortest-unsorted-continuous-subarray/README.md new file mode 100644 index 0000000..418f67a --- /dev/null +++ b/0581_shortest-unsorted-continuous-subarray/README.md @@ -0,0 +1,29 @@ +Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending 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? \ No newline at end of file diff --git a/0581_shortest-unsorted-continuous-subarray/python3/solution.py b/0581_shortest-unsorted-continuous-subarray/python3/solution.py new file mode 100644 index 0000000..d8cef67 --- /dev/null +++ b/0581_shortest-unsorted-continuous-subarray/python3/solution.py @@ -0,0 +1,39 @@ +class Solution: + def findUnsortedSubarray(self, nums: List[int]) -> int: + min_unsorted = float("inf") + max_unsorted = float("-inf") + + # Find min and max element in the unsorted portion + for i, num in enumerate(nums): + if not self.is_sorted(i, nums): + min_unsorted = min(min_unsorted, num) + max_unsorted = max(max_unsorted, num) + + if min_unsorted == float("inf"): + return 0 + + # Find right places for min and max elements from previous + # step in the "sorted" section of the array + left = 0 + while nums[left] <= min_unsorted: + left += 1 + + right = len(nums) - 1 + while nums[right] >= max_unsorted: + right -= 1 + + return right - left + 1 + + def is_sorted(self, i: int, nums: List[int]) -> bool: + n = len(nums) + + if n <= 1: + return True + + if i == 0: + return nums[i] <= nums[i + 1] + + if i == n - 1: + return nums[i - 1] <= nums[i] + + return nums[i - 1] <= nums[i] <= nums[i + 1]