Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active September 4, 2021 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YonatanKra/84c6236ded2cf8fb384e485aa354d68f to your computer and use it in GitHub Desktop.
Save YonatanKra/84c6236ded2cf8fb384e485aa354d68f to your computer and use it in GitHub Desktop.
function getNestedArraysMaxLength(inputArray) {
let maxLength = -Infinity;
const memory = [];
inputArray.forEach(value => {
memory[value] = findSeriesLength(inputArray, value, memory);
maxLength = Math.max(maxLength, memory[value]);
});
return maxLength;
}
function findSeriesLength(arr, nextValue, memory) {
const series = {[nextValue]: true};
while (true) {
nextValue = arr[nextValue];
if (memory[nextValue]) {
return memory[nextValue];
}
if (series[nextValue]) {
return Object.keys(series).length;
}
series[nextValue] = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment