Length of shortest unsorted array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

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.

For example, if the input to the function is −

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

Then the output should be −

const output = 5;

Output Explanation

Because if we sort [7, 5, 9, 11, 10], the whole array will be sorted.

Example

Following is the code −

 Live Demo

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
   while (sorted[start] === arr[start] && start < arr.length) {
      start += 1
   }
   while (sorted[end] === arr[end] && end >= 0) {
      end -= 1
   }
   return end >= start ? end - start + 1 : 0
}
console.log(shortestLength(arr));

Output

Following is the console output −

5

Updated on: 21-Apr-2021

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements