Algorithm
Problem Name: 581. Shortest Unsorted Continuous Subarray
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.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [1,2,3,4] Output: 0
Example 3:
Input: nums = [1] Output: 0
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int findUnsortedSubarray(int[] nums) {
Stack stack = new Stack<>();
int start = nums.length;
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) {
start = Math.min(start, stack.pop());
}
stack.push(i);
}
stack.clear();
int end = 0;
for (int i = nums.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
end = Math.max(end, stack.pop());
}
stack.push(i);
}
return end - start > 0 ? end - start + 1 : 0;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const findUnsortedSubarray = function(nums) {
let stack = []
let left = nums.length
let right = 0
for(let i = 0; i < nums.length; i++) {
while(stack.length > 0 && nums[stack[stack.length - 1]] > nums[i]) {
left = Math.min(left, stack.pop())
}
stack.push(i)
}
stack = []
for(let i = nums.length - 1; i >= 0; i--) {
while(stack.length > 0 && nums[stack[stack.length - 1]] < nums[i] ) {
right = Math.max(right, stack.pop())
}
stack.push(i)
}
return right > left ? right - left + 1: 0
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
arr = sorted(nums)
i = 0
for i in range(len(arr)):
if arr[i] != nums[i]:
for j in range(len(arr) - 1, -1, -1):
if arr[j] != nums[j]:
return j - i + 1
return 0
Copy The Code &
Try With Live Editor
Input
#4 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _0581_ShortestUnsortedContinuousSubarray
{
public int FindUnsortedSubarray(int[] nums)
{
int min = int.MaxValue, max = int.MinValue;
var flag = false;
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] < nums[i - 1])
flag = true;
if (flag)
min = Math.Min(min, nums[i]);
}
flag = false;
for (int i = nums.Length - 2; i >= 0; i--)
{
if (nums[i] > nums[i + 1])
flag = true;
if (flag)
max = Math.Max(max, nums[i]);
}
int l, r;
for (l = 0; l < nums.Length; l++)
if (min < nums[l])
break;
for (r = nums.Length - 1; r >= 0; r--)
if (max > nums[r])
break;
return r >= l ? r - l + 1 : 0;
}
}
}
Copy The Code &
Try With Live Editor
Input