<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>

<p>Return <em>the shortest such subarray and output its length</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

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

<p><strong class="example">Example 3:</strong></p>

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

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        
        // from starting, find next smaller position in the right

        stack<int> stack;
        vector<int> nextSmaller(n);

        for (int i = n - 1; i >= 0; i--) {
            while (!stack.empty() && nums[i] <= nums[stack.top()]) {
                stack.pop();
            }
            nextSmaller[i] = stack.empty() ? -1 : stack.top();
            stack.push(i);
        }


        // from end, find next greater positon in the left

        while (!stack.empty()) stack.pop();
        vector<int> prevGreater(n);

        for (int i = 0; i < n; i++) {
            while (!stack.empty() && nums[i] >= nums[stack.top()]) {
                stack.pop();
            }
            prevGreater[i] = stack.empty() ? -1 : stack.top();
            stack.push(i);
        }

        int l = -1, r = -1;

        for (int i = 0; i < n; i++) {
            int j = nextSmaller[i];
            if (j != -1) {
                    l = i;
                    break;
            } 
        }

        for (int i = n - 1; i >= 0; i--) {
            int j = prevGreater[i];
            if (j != -1) {
                    r = i;
                    break;
            } 
        }

        if (l == -1 || r == -1) return 0;
        return r - l + 1;
    }
};

// 2 3 4 3 5

// 2 3 3 5 4


31800