Share my JavaScript solution

• The solution is long, but that's what I have in mind when I see the question :) Basically the idea is search for a path in the graph and keep track of the product.

``````/**
* @param {string[][]} equations
* @param {number[]} values
* @param {string[][]} queries
* @return {number[]}
*/
const calcEquation = (equations, values, queries) => {
const result = [];

// Step 1. Build the undirected graph with adjacency list

// Step 2. For each query, try to find a path in the graph
// that can link the nodes in the query
for (let i = 0; i < queries.length; i++) {
const [from, to] = queries[i];
const value = dfs(adjList, from, to, 1, new Set());

// If value is null, that means there's no such path
result.push(value ? value : -1.0);

if (value) {
// Update the graph to avoid duplicate computation
}
}

return result;
};

/**
* @param {Map<string, Map<string, number>>} adjList
* @param {string} node
* @param {string} to
* @param {number} product
* @param {Set} visited
*/
const dfs = (adjList, node, to, product, visited) => {
}

visited.add(node); // Mark the current node as visited

for (let i = 0; i < neighbors.length; i++) {
const v = neighbors[i];
const current = product * adjList.get(node).get(v);

if (v === to) {
// Found the path, return the product
return current;
}

if (!visited.has(v)) {
// Continue to search for the path
const value = dfs(adjList, v, to, current, visited);

if (value) {
return value;
}
}
}

return null;
};

const buildGraph = (equations, values) => {

for (let i = 0; i < equations.length; i++) {
const [from, to] = equations[i];
const value = values[i];

}