Last active
September 3, 2020 05:50
-
-
Save anthonydmays/09636abce6ed7c0ed2267d0ec89c2a9d to your computer and use it in GitHub Desktop.
Given an array of integers, write a method to find indices m and n such that if you sorted elements m through n, the entire array would be sorted. Minimize n - m (that is, find the smallest such sequence). Watch interview coach and Google engineer Anthony D. Mays solve this problem in real time on YouTube: https://youtu.be/Q8HlPVWdssk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given an array of integers, write a method to find indices m and n such that | |
* if you sorted elements m through n, the entire array would be sorted. | |
* Minimize n - m (that is, find the smallest such sequence). | |
*/ | |
function findSortableIndices(arr) { | |
let i = 1; | |
let max = arr[0]; | |
let minUnsorted = Number.MAX_VALUE; | |
let start, end; | |
if (!arr || !arr.length || arr.length === 1) { | |
return []; | |
} | |
// Note: corrected from original video :(. That's it though! | |
while (i < arr.length) { | |
if (arr[i] < max) { | |
if (!start) { | |
start = i; | |
} | |
end = i; | |
} else { | |
max = arr[i]; | |
} | |
if (start && arr[i] < minUnsorted) { | |
minUnsorted = arr[i]; | |
} | |
++i; | |
} | |
if (!start) { | |
return []; | |
} | |
for (let i = 0; i < start; ++i) { | |
if (arr[i] > minUnsorted) { | |
start = i; | |
break; | |
} | |
} | |
return [start, end]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment