Skip to content

Instantly share code, notes, and snippets.

@anthonydmays
Last active September 3, 2020 05:50
Show Gist options
  • Save anthonydmays/09636abce6ed7c0ed2267d0ec89c2a9d to your computer and use it in GitHub Desktop.
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.
/**
* 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