Longest Path With Different Adjacent Characters LeetCode solution in JavaScript

1
var longestPath = function (parent, s) {
2
const adjList = parent.reduce(
3
(adjList, parent, node) => {
4
if (parent < 0) return adjList;
5
adjList[parent].push(node);
6
return adjList;
7
},
8
new Array(parent.length).fill(0).map(() => [])
9
);
10

11
let longest = 1;
12

13
const getLongest = (node) => {
14
let maxChild1 = 0;
15
let maxChild2 = 0;
16

17
adjList[node].forEach((child) => {
18
const childLength = getLongest(child);
19

20
// child letter matches our node, so we can't use it
21
if (s[child] === s[node]) return;
22

23
// compare and update the longest two child paths
24
if (childLength > maxChild1) {
25
maxChild2 = maxChild1;
26
maxChild1 = childLength;
27
} else if (childLength > maxChild2) {
28
maxChild2 = childLength;
29
}
30
});
31

32
// longest loop
33
longest = Math.max(longest, maxChild1 + maxChild2 + 1);
34

35
// return longest path up the tree
36
return 1 + maxChild1;
37
};
38

39
getLongest(0);
40

41
return longest;
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0