Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created August 30, 2019 21:38
Show Gist options
  • Save jubishop/7dba3f0f5ebb7f0808e91adec8db46b5 to your computer and use it in GitHub Desktop.
Save jubishop/7dba3f0f5ebb7f0808e91adec8db46b5 to your computer and use it in GitHub Desktop.
const tracker = {};
const NEIGHBOR_ABOVE = "above";
const NEIGHBOR_BELOW = "below";
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);
}
function longestConsecutive(nums) {
let longestConsecutiveLength = 0;
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;
}
}
return longestConsecutiveLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment