Shortest Unsorted Continuous Subarray

Updated on 24 June, 2025
Shortest Unsorted Continuous Subarray header image

Problem Statement

The task requires finding a contiguous subarray in an integer array nums. This subarray, when sorted, should render the entire array sorted in a non-decreasing order. The goal is to identify the shortest such subarray and determine its length. This could help visualize how closely an array is to being fully sorted and what minimal changes (in terms of sorting a small segment) are required to completely sort it.

Examples

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

Approach and Intuition

Analyzing the Problem with Examples

  1. Example 1:

    • Input: nums = [2,6,4,8,10,9,15]
    • The subarray that disrupts the sorting is [6, 4, 8, 10, 9]. Sorting this part alone would render the entire array sorted.
    • The length of this subarray is 5.
  2. Example 2:

    • Input: nums = [1,2,3,4]
    • The array is already sorted in non-decreasing order. Thus, no subarray sorting is needed.
    • The shortest subarray length would therefore be 0.
  3. Example 3:

    • Input: nums = [1]
    • This single-element array trivially satisfies the non-decreasing order requirement.
    • The length of the subarray needed for sorting, in this case, would once again be 0.

Steps to Derive the Solution

  1. Identify the first point from the beginning of the array where elements are not in the expected order (increasing).
  2. Identify the last point from the end of the array where elements deviate from the desired order.
  3. The subarray contained within these two points is the candidate for sorting.
  4. Calculate the length of this subarray for the result. If no such points exist (i.e., the entire array is already sorted), the length will be 0.

By adhering to these steps, one can determine the minimal effort required to make the entire array sorted through a localized sort operation.

Solutions

  • Java
java
public class Solution {
    public int minimumUnsortedSubarray(int[] elements) {
        int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;
        boolean unsorted = false;
        for (int i = 1; i < elements.length; i++) {
            if (elements[i] < elements[i - 1])
                unsorted = true;
            if (unsorted)
                smallest = Math.min(smallest, elements[i]);
        }
        unsorted = false;
        for (int i = elements.length - 2; i >= 0; i--) {
            if (elements[i] > elements[i + 1])
                unsorted = true;
            if (unsorted)
                largest = Math.max(largest, elements[i]);
        }
        int start, end;
        for (start = 0; start < elements.length; start++) {
            if (smallest < elements[start])
                break;
        }
        for (end = elements.length - 1; end >= 0; end--) {
            if (largest > elements[end])
                break;
        }
        return end - start < 0 ? 0 : end - start + 1;
    }
}

This Java program determines the length of the shortest contiguous subarray that, if sorted, would result in the entire array being sorted. The method minimumUnsortedSubarray in the Solution class accepts an integer array elements as input and proceeds in several stages to find the solution:

  • Identifying Unsorted Portions:

    • unsorted flag tracks segments of the array that are improperly ordered.
    • Traverses the array from left to right. If any element is smaller than its predecessor, this indicates the start of an unsorted segment.
    • Proceeds with a right-to-left pass to locate where elements are larger than their subsequent ones, again indicating disorder.
  • Determine Boundaries for Sorting:

    • Computes the minimum value within the identified unsorted region during the left-to-right traversal.
    • Similarly, computes the maximum value during the right-to-left pass.
  • Identify the Unsorted Subarray:

    • From the start of the array to its end, seeks the first position where the smallest value of the unsorted subarray found should be inserted to maintain sorted order.
    • Similarly, from the end back to the start, locates the position where the largest value of the unsorted subarray fits in a sorted order.
  • Calculating Subarray Size:

    • Determines the length of the subarray that needs sorting from the indices identified. If the calculated length shows a negative number, it returns 0 (indicating the entire array is already sorted), otherwise, it provides the length of the subarray by adding one to the difference of end and start positions.

This approach efficiently pinpoints the smallest section of the array that needs sorting to optimize the entire array, and it runs with time complexity dependent largely on array traversal operations.

Comments

No comments yet.