Shortest Unsorted Continuous Subarray

Problem Id: 581 Difficulty: Medium


Intuition

Solution


class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        sorted_nums = sorted(nums)
        lo, hi = len(nums), 0
        for i in range(len(nums)):
            if nums[i] != sorted_nums[i]:
                lo = min(lo, i)
                hi = max(hi, i)
        if lo > hi:
            return 0
        return hi - lo + 1