103. Shortest Unsorted Continuous Subarray

MediumArrayArray

Given an integer array nums, find the smallest subarray that if sorted would make the whole array sorted. Return the length of this subarray. If the array is already sorted, return 0.

Input: Integer array nums.

Output: Integer — length of shortest unsorted subarray.

Examples

Example 1
Input: [2,6,4,8,10,9,15]
Output: 5
Explanation: Sort [6,4,8,10,9] → [2,4,6,8,9,10,15]. Length 5.
Example 2
Input: [1,2,3,4,5]
Output: 0
Explanation: Already sorted.
Example 3
Input: [5,4,3,2,1]
Output: 5
Explanation: Must sort entire array.

Constraints

Asked by

DeloitteGoogleMicrosoftAmazonBloombergMeta
Solve this problem in the editor →