Length of shortest unsorted array in JavaScript

We are required to write a JavaScript function that takes in an array of numbers and finds the length of the shortest continuous subarray that, when sorted, makes the entire array sorted in ascending order.

Our function needs to find the length of one continuous subarray such that if we only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

Problem Example

For example, if the input array is:

const arr = [3, 7, 5, 9, 11, 10, 16];
console.log("Original array:", arr);
Original array: [3, 7, 5, 9, 11, 10, 16]

The output should be 5 because if we sort the subarray [7, 5, 9, 11, 10] (positions 1-5), the whole array becomes sorted: [3, 5, 7, 9, 10, 11, 16].

Solution Approach

The algorithm works by comparing the original array with its sorted version to find the leftmost and rightmost positions where elements differ:

Finding Shortest Unsorted Subarray Original: 3 7 5 9 11 10 16 Sorted: 3 5 7 9 10 11 16 Start End Unsorted subarray length: 5

Implementation

const arr = [3, 7, 5, 9, 11, 10, 16];

const shortestLength = (arr = []) => {
    const sorted = [...arr].sort((a, b) => a - b);
    let start = 0;
    let end = sorted.length - 1;
    
    // Find the first position where elements differ
    while (sorted[start] === arr[start] && start < arr.length) {
        start += 1;
    }
    
    // Find the last position where elements differ
    while (sorted[end] === arr[end] && end >= 0) {
        end -= 1;
    }
    
    // Return length of subarray that needs sorting
    return end >= start ? end - start + 1 : 0;
};

console.log("Array:", arr);
console.log("Shortest unsorted subarray length:", shortestLength(arr));
Array: [3, 7, 5, 9, 11, 10, 16]
Shortest unsorted subarray length: 5

How It Works

The algorithm follows these steps:

  1. Create a sorted copy of the original array
  2. Find the leftmost position where the original and sorted arrays differ
  3. Find the rightmost position where they differ
  4. Calculate the length of the subarray between these positions

Additional Examples

// Already sorted array
console.log("Already sorted:", shortestLength([1, 2, 3, 4, 5]));

// Reverse sorted array
console.log("Reverse sorted:", shortestLength([5, 4, 3, 2, 1]));

// Single element out of place
console.log("Single element:", shortestLength([1, 3, 2, 4, 5]));
Already sorted: 0
Reverse sorted: 5
Single element: 2

Time and Space Complexity

Aspect Complexity Explanation
Time O(n log n) Sorting the array dominates
Space O(n) Creating a copy of the array

Conclusion

This algorithm efficiently finds the shortest subarray that needs sorting by comparing the original array with its sorted version. It's particularly useful for optimization problems where minimal sorting is required.

Updated on: 2026-03-15T23:19:00+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements