Evaluate Division LeetCode solution in JavaScript

1
var calcEquation = function (equations, values, queries) {
2
const res = [];
3

4
for (let i = 0; i < queries.length; i++) {
5
const currQuery = queries[i];
6

7
const [currStart, currDestination] = currQuery;
8

9
const adj = {};
10

11
const additionalEdges = [];
12
const additionalValues = [];
13

14
const visited = new Set();
15

16
equations.forEach((el, idx) => {
17
const [to, from] = el;
18
const val = values[idx];
19

20
additionalEdges.push([from, to]);
21
additionalValues.push(1 / val);
22
});
23

24
values = [...values, ...additionalValues];
25
let idx = 0;
26
for (const [from, to] of [...equations, ...additionalEdges]) {
27
if (!(from in adj)) adj[from] = [];
28

29
adj[from].push([to, values[idx]]);
30

31
idx++;
32
}
33

34
if (!(currStart in adj) || !(currDestination in adj)) {
35
res.push(-1);
36
continue;
37
}
38

39
if (currStart === currDestination) {
40
res.push(1);
41
continue;
42
}
43

44
let currEvaluation = 1;
45
let found = false;
46
const subResult = dfs(currStart);
47
if (!found) res.push(-1);
48

49
function dfs(node) {
50
if (!node) return null;
51
if (node === currDestination) {
52
return true;
53
}
54

55
const children = adj[node]; // [ [to, val] ]
56

57
if (!children) return false;
58

59
for (const child of children) {
60
if (visited.has(node)) continue;
61
visited.add(node);
62

63
currEvaluation = currEvaluation * child[1];
64

65
if (dfs(child[0]) === true) {
66
!found && res.push(currEvaluation);
67
found = true;
68
return;
69
}
70
visited.delete(node);
71
currEvaluation /= child[1];
72
}
73
}
74
}
75
return res;
76
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0