# 581. Shortest Unsorted Continuous Subarray (Easy)

https://leetcode.com/problems/shortest-unsorted-continuous-subarray/

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

```Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
```

Note:

1. Then length of the input array is in range [1, 10,000].
2. The input array may contain duplicates, so ascending order here means <=< b="">.

## Solutions

``````class Solution {

// the intuition is find the preceding ascending subsequence and the trailing ascending subsequence.
// But what if the array is [2, 3, 1,5, 10, 7, 8, 9]

// The intuition is half correct and half wrong.

// Once sort out the preceding and trailing subsequence, the possible continuous unsorted comes out.
// Then find out the min and max of the unsorted subsequence. Compared the min with the preceding
// ordered subsequence, values larger than min should be included into the unsorted subsequence.
// The same applies to the max and the trailing subsequence.

public int findUnsortedSubarray(int[] nums) {
if (nums == null && nums.length <= 1) {
return 0;
}

int len = nums.length;

// preceding subsequence length
int preLen = 0;

// sort out the preceding ordered subsequence
for (int i = 0; i < len - 1; i++) {
if (nums[i] > nums[i + 1]) {
break;
}

preLen++;
}

// if the given array is sorted, return directly
if (preLen == len - 1) {
return 0;
}

// trailing subsequence length
int traLen = 0;

// sort out the trailing ordered subsequence
for (int i = len - 1; i > 0; i--) {
if (nums[i] < nums[i - 1]) {
break;
}

traLen++;
}

// sort out the min and max within unsorted subsequence

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

// [1, 3, 2, 4], preLen = 1, traLen = 1
for (int i = preLen; i < len - traLen; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}

// extra elements that need to be included into desired subsequence
int extra = 0;

// compare min with preceding subsequence
for (int i = 0; i < preLen; i++) {
if (nums[i] > min) {
extra++;
}
}

// compare max with trailing subsequence
for (int i = len - 1; i >= len - traLen; i--) {
if (nums[i] < max) {
extra++;
}
}

return len - preLen - traLen + extra;
}
}
``````