Shortest Unsorted Continuous Subarray — LeetCode 581 Python Solution

MediumStackGreedyArrayTwo PointersSortingMonotonic Stack
Problem
#581
Pattern
Stack
Reading time
2 min

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

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview