Shortest Unsorted Continuous Subarray — LeetCode 581 Python Solution
- Problem
- #581
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- 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.
Python solution
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 + 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 581. Shortest Unsorted Continuous Subarray is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 581. Shortest Unsorted Continuous Subarray?
- LeetCode 581. Shortest Unsorted Continuous Subarray is rated Medium on LeetCode.
- What is the time complexity of LeetCode 581. Shortest Unsorted Continuous Subarray?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 581. Shortest Unsorted Continuous Subarray?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 581. Shortest Unsorted Continuous Subarray cover?
- LeetCode 581. Shortest Unsorted Continuous Subarray is tagged Stack, Greedy, Array, Two Pointers, Sorting and Monotonic Stack on LeetCode.