Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created April 13, 2020 03:57
Show Gist options
  • Save RP-3/fd644b8f4b5c66c56a9cf9041a20c95a to your computer and use it in GitHub Desktop.
Save RP-3/fd644b8f4b5c66c56a9cf9041a20c95a to your computer and use it in GitHub Desktop.
const longestPath = (adjList) => {
const graph = {};
adjList.forEach(([from, to]) => {
if(!graph[from]) graph[from] = new Set();
graph[from].add(to);
});
const memo = {}; // node -> longestPathLength starting at node
let result = 0;
for(let start in graph){
if(!memo.hasOwnProperty(start)) memo[start] = _longestPath(start);
result = Math.max(result, memo[start]);
}
return result;
function _longestPath(startNode){
if(memo.hasOwnProperty(startNode)) return memo[startNode];
if(!graph[startNode]) return 0;
let maxPathLength = 0;
for(let adj of graph[startNode]){
maxPathLength = Math.max(maxPathLength, 1 + _longestPath(adj));
}
return memo[startNode] = maxPathLength;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment