Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
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:
- Create a sorted copy of the original array
- Find the leftmost position where the original and sorted arrays differ
- Find the rightmost position where they differ
- 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.
