666. Shortest Unsorted Continuous Subarray

HardStackMonotonic StackArray

Given an array nums, find the shortest contiguous subarray such that sorting just that subarray makes the whole array sorted in ascending order, and return its length (0 if already sorted). The input is JSON {nums}.

Input: JSON {nums}.

Output: Integer — the length of the shortest such subarray.

Examples

Example 1
Input: {"nums":[2,6,4,8,10,9,15]}
Output: 5
Explanation: Sorting indices 1..5 sorts everything.
Example 2
Input: {"nums":[1,2,3,4]}
Output: 0
Explanation: Already sorted.
Example 3
Input: {"nums":[2,1]}
Output: 2
Explanation: Swap the two.

Constraints

Asked by

DeloitteGoogleMicrosoftAmazonBloombergMeta
Solve this problem in the editor →