Created
August 30, 2019 21:35
-
-
Save jubishop/5b35dd6c907b37c2a186e2072c968579 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 longestConsecutive(nums) { | |
let longestConsecutiveLength = 0, | |
longestKey; // FOR TESTING: This stores the key of a number in the longest sequence, used to build the list for display | |
const tracker = {}; | |
const NEIGHBOR_ABOVE = "above"; | |
const NEIGHBOR_BELOW = "below"; | |
for (let i = 0; i < nums.length; i++) { | |
let currentValue = nums[i], | |
neighborAbove = getNeighbor(currentValue, NEIGHBOR_ABOVE), | |
neighborBelow = getNeighbor(currentValue, NEIGHBOR_BELOW), | |
aboveConsecutiveLength = (tracker[neighborAbove] !== undefined ? tracker[neighborAbove] : 0), | |
belowConsecutiveLength = (tracker[neighborBelow] !== undefined ? tracker[neighborBelow] : 0), | |
newConsecutiveLength = aboveConsecutiveLength + 1 + belowConsecutiveLength; | |
tracker[currentValue] = newConsecutiveLength; | |
if (aboveConsecutiveLength > 0) { | |
updateConnected(currentValue, newConsecutiveLength, NEIGHBOR_ABOVE); | |
} | |
if (belowConsecutiveLength > 0) { | |
updateConnected(currentValue, newConsecutiveLength, NEIGHBOR_BELOW); | |
} | |
if (newConsecutiveLength > longestConsecutiveLength) { | |
longestConsecutiveLength = newConsecutiveLength; | |
longestKey = currentValue; | |
} | |
} | |
function updateConnected(current, value, direction) { | |
const neighbor = getNeighbor(current, direction); | |
if (neighbor !== false) { | |
tracker[neighbor] = value; | |
updateConnected(neighbor, value, direction); | |
} | |
} | |
function getNeighbor(current, direction) { | |
if (direction === NEIGHBOR_ABOVE) { | |
neighbor = current + 1; | |
} else if (direction === NEIGHBOR_BELOW) { | |
neighbor = current - 1; | |
} else { | |
console.error("Unexpected direction"); | |
} | |
return (tracker[neighbor] !== undefined ? neighbor : false); | |
} | |
/* FOR TESTING: To build the list of consecutive numbers to display */ | |
const consecutiveList = [longestKey]; | |
function buildConsecutiveList(key, direction) { | |
const neighbor = getNeighbor(key, direction); | |
if (neighbor !== false) { | |
consecutiveList.push(neighbor); | |
buildConsecutiveList(neighbor, direction); | |
} | |
} | |
buildConsecutiveList(longestKey, NEIGHBOR_ABOVE); | |
buildConsecutiveList(longestKey, NEIGHBOR_BELOW); | |
return longestConsecutiveLength; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment