greedy December 26, 2022

Shortest unsorted continuous subarray

Time O(nlog(n)) Space O(n) Open original problem

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)