Shortest Unsorted Continuous Subarray

Given an integer array `nums`, find the shortest continuous subarray such that, if you sort only that subarray in non-decreasing order, the whole array becomes sorted in non-decreasing order. Return the length of that subarray (0 if the array is already sorted).

30:00

Shortest Unsorted Continuous Subarray
medium
Free written solution
Topics
Companies

Given an integer array nums, find the shortest continuous subarray such that, if you sort only that subarray in non-decreasing order, the whole array becomes sorted in non-decreasing order. Return the length of that subarray (0 if the array is already sorted).

Example 1:
Input: {"nums":[2,6,4,8,10,9,15]}
Output: 5
Constraints:
  • 1≤nums.length≤1041 \leq \text{nums.length} \leq 10^4

  • −105≤nums[i]≤105-10^5 \leq \text{nums}[i] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[2,6,4,8,10,9,15]}
pass 1 → running max finds end
pass 2 ← running min finds start

nums

2

0

6

1

4

2

8

3

10

4

9

5

15

6

■ scanning■ below max on its left■ above min on its right

Set end = -1 and start = 0 so that an already sorted array gives end - start + 1 = 0.

start = 0
end = -1
end - start + 1 = ?
Variables
VariableValue
start0
end-1
DepthFunction Call
Stack empty
0/15