Skip to main content

Shortest Unsorted Continuous Subarray

MediumArraySorting

Description

Given an integer array nums, find the shortest continuous subarray that, when sorted, results in the whole array being sorted.

Examples

Input:nums = [2,6,4,8,10,9,15]
Output:5
Explanation:

Subarray [6,4,8,10,9] (indices 1-5) needs sorting. Length 5. When sorted, whole array becomes sorted.

Input:nums = [1,2,3,4]
Output:0
Explanation:

The array is already sorted in ascending order, so no subarray needs to be sorted.

Input:nums = [1]
Output:0
Explanation:

A single element is trivially sorted, so no subarray needs to be sorted.

Constraints

  • 1 ≤ nums.length ≤ 10⁴

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.