Created
October 8, 2019 21:48
-
-
Save ilatif/e80fe617d6d1d35c18d585b83a6989a7 to your computer and use it in GitHub Desktop.
AlgoExpert Largest Range - https://www.algoexpert.io/questions/Largest%20Range
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
function largestRange(array) { | |
if (array.length === 1) { | |
return [array[0], array[0]]; | |
} | |
var hash = {}; | |
hash[array[0]] = []; | |
var current = array[0]; | |
for (var i = 1; i < array.length; i++) { | |
var temp = array[i]; | |
if (!hash[temp]) { | |
hash[temp] = []; | |
} | |
if (hash[temp - 1]) { | |
hash[temp].push(temp - 1); | |
} | |
if (hash[temp + 1]) { | |
hash[temp].push(temp + 1); | |
} | |
if (hash[temp - 1]) { | |
hash[temp - 1].push(temp); | |
} | |
if (hash[temp + 1]) { | |
hash[temp + 1].unshift(temp); | |
} | |
} | |
var keys = Object.keys(hash), max = []; | |
for (var i = 0; i < keys.length; i++) { | |
var key = keys[i]; | |
var arr = hash[key]; | |
if (arr.length === 1 && arr[0] > key) { | |
var a = hash[arr[0]], temp = [parseInt(key), arr[0]]; | |
for (var j = 1; j < keys.length; j++) { | |
if (!a || !a.length || a.length === 1) { | |
break; | |
} | |
if (a[a.length - 1]) { | |
temp.push(a[a.length - 1]); | |
} | |
a = hash[a[a.length - 1]]; | |
} | |
if (temp.length > max.length) { | |
max = temp; | |
} | |
} | |
} | |
return [max[0], max[max.length - 1]]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment