> For the complete documentation index, see [llms.txt](https://chiragjain.gitbook.io/neetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chiragjain.gitbook.io/neetcode/581-shortest-unsorted-continuous-subarray.md).

# 581. Shortest Unsorted Continuous Subarray

## Medium

***

Given an integer array `nums`, 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.

Return *the shortest such subarray and output its length*.

&#x20;

**Example 1:**

<pre><code>Input: nums = [2,6,4,8,10,9,15]
<strong>Output:
</strong> 5
<strong>Explanation:
</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</code></pre>

**Example 2:**

<pre><code>Input: nums = [1,2,3,4]
<strong>Output:
</strong> 0
</code></pre>

**Example 3:**

<pre><code>Input: nums = [1]
<strong>Output:
</strong> 0
</code></pre>

&#x20;

**Constraints:**

* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`

&#x20;

**Follow up:** Can you solve it in `O(n)` time complexity?
