← Home

581. Shortest Unsorted Continuous Subarray

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
581

This is one of those problems where the clean idea matters more than the amount of code. For 581. Shortest Unsorted Continuous Subarray, the solution in this repository is mainly a two pointers solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, greedy.

The notes already sitting in the source point us in the right direction:

  • Sorting
  • time: O(NlogN), space: O(N)

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findUnsortedSubarray.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NlogN), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Sorting
02//Runtime: 80 ms, faster than 58.67% of C++ online submissions for Shortest Unsorted Continuous Subarray.
03//Memory Usage: 27.6 MB, less than 7.63% of C++ online submissions for Shortest Unsorted Continuous Subarray.
04//time: O(NlogN), space: O(N)
05class Solution {
06public:
07    int findUnsortedSubarray(vector<int>& nums) {
08        int n = nums.size();
09        if(n <= 1) return 0;
10        
11        vector<int> sorted = nums;
12        sort(sorted.begin(), sorted.end());
13        
14        int start = -1, end = -1;
15        for(int i = 0; i < n; ++i){
16			if(nums[i] != sorted[i]){
17                start = i;
18                break;
19            }
20        }
21        if(start == -1) return 0;
22        
23        for(int i = n-1; i >= 0; --i){
24			if(nums[i] != sorted[i]){
25                end = i;
26                break;
27            }
28        }
29        return end - start + 1;
30    }
31};
32
33//Approach 2: Better Brute Force
34//TLE
35//211 / 307 test cases passed.
36//time: O(N^2), space: O(1)
37class Solution {
38public:
39    int findUnsortedSubarray(vector<int>& nums) {
40        int n = nums.size();
41        int l = n, r = -1;
42        
43        for(int i = 0; i < n; ++i){
44            for(int j = i+1; j < n; ++j){
45                if(nums[j] < nums[i]){
46                    l = min(l, i);
47                    r = max(r, j);
48                }
49            }
50        }
51        
52        //r-l+1 could be negative
53        return max(0, r-l+1);
54    }
55};
56
57//Approach 4: Using Stack
58//Runtime: 72 ms, faster than 63.01% of C++ online submissions for Shortest Unsorted Continuous Subarray.
59//Memory Usage: 28 MB, less than 7.65% of C++ online submissions for Shortest Unsorted Continuous Subarray.
60//time: O(NlogN), space: O(N)
61class Solution {
62public:
63    int findUnsortedSubarray(vector<int>& nums) {
64        int n = nums.size();
65        
66        stack<int> stk;
67        
68        int l = n, r = -1;
69        
70        for(int i = 0; i < n; ++i){
71            //pop all previous index s.t. they are larger than current element
72            //find the min l s.t. nums[l] is not at its right position
73            while(!stk.empty() && nums[stk.top()] > nums[i]){
74                l = min(l, stk.top()); stk.pop();
75                // cout << "l: " << l << ", " << i << endl;
76                // r = i; //this is wrong!
77            }
78            
79            stk.push(i);
80        }
81        
82        stk = stack<int>(); //!
83        for(int i = n-1; i >= 0; --i){
84            //find the max r s.t. nums[r] is not at its right position
85            while(!stk.empty() && nums[stk.top()] < nums[i]){
86                r = max(r, stk.top()); stk.pop();
87                // cout << "r: " << r << ", " << i << endl;
88            }
89            stk.push(i);
90        }
91        
92        // cout << "[" << l << ", " << r << "]" << endl;
93        
94        return max(0, r-l+1);
95    }
96};
97
98//Approach 5: Without Using Extra Space
99//Runtime: 52 ms, faster than 94.59% of C++ online submissions for Shortest Unsorted Continuous Subarray.
100//Memory Usage: 26.8 MB, less than 7.65% of C++ online submissions for Shortest Unsorted Continuous Subarray.
101//time: O(N), space: O(1)
102class Solution {
103public:
104    int findUnsortedSubarray(vector<int>& nums) {
105        int n = nums.size();
106        bool flag = false;
107        int minv = INT_MAX, maxv = INT_MIN;
108        
109        for(int i = 1; i < n; ++i){
110            //see the first unsorted element
111            if(nums[i] < nums[i-1]) flag = true;
112            //start to record the min element in the unsorted array
113            if(flag) minv = min(minv, nums[i]);
114        }
115        
116        flag = false;
117        for(int i = n-2; i >= 0; --i){
118            if(nums[i] > nums[i+1]) flag = true;
119            if(flag) maxv = max(maxv, nums[i]);
120        }
121        
122        int l, r;
123        for(l = 0; l < n; ++l){
124            if(nums[l] > minv) break;
125        }
126        //minv should be at l
127        
128        for(r = n-1; r >= 0; --r){
129            if(nums[r] < maxv) break;
130        }
131        //maxv should be at r
132        
133        return max(r-l+1, 0);
134    }
135};

Cost

Complexity

Time
O(NlogN), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.