Skip to main content
Back to problems
#581
Medium Algorithms

Shortest unsorted continuous subarray

Array Two Pointers Stack Greedy Sorting Monotonic Stack
38.0% acceptance
Jan 13, 2026
8014
274
Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order. Return the shortest such subarray and output its length.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_unsorted_subarray(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut end = -1i32;
    let mut start = 0i32;
    let mut max_val = i32::MIN;
    let mut min_val = i32::MAX;
    for i in 0..n {
      if nums[i] < max_val { end = i as i32; } else { max_val = nums[i]; }
      let j = n - 1 - i;
      if nums[j] > min_val { start = j as i32; } else { min_val = nums[j]; }
    }
    if end == -1 { 0 } else { end - start + 1 }
  }
}