Shortest unsorted continuous subarray

December 26, 2022

greedy

Problem URL: Shortest unsorted continuous subarray

We will sort the array and find the first and last index where the elements are different.

class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        res = [i for (i, (a, b)) in enumerate(zip(nums, sorted(nums))) if a != b]
        return 0 if not res else res[-1] - res[0] + 1

Time complexity: O(nlog(n))
Space complexity: O(n)