|
| 1 | +/** |
| 2 | + * 399. Evaluate Division |
| 3 | + * https://leetcode.com/problems/evaluate-division/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an array of variable pairs equations and an array of real numbers values, |
| 7 | + * where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. |
| 8 | + * Each Ai or Bi is a string that represents a single variable. |
| 9 | + * |
| 10 | + * You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query |
| 11 | + * where you must find the answer for Cj / Dj = ?. |
| 12 | + * |
| 13 | + * Return the answers to all queries. If a single answer cannot be determined, return -1.0. |
| 14 | + * |
| 15 | + * Note: The input is always valid. You may assume that evaluating the queries will not |
| 16 | + * result in division by zero and that there is no contradiction. |
| 17 | + * |
| 18 | + * Note: The variables that do not occur in the list of equations are undefined, so the |
| 19 | + * answer cannot be determined for them. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string[][]} equations |
| 24 | + * @param {number[]} values |
| 25 | + * @param {string[][]} queries |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var calcEquation = function(equations, values, queries) { |
| 29 | + const map = equations.reduce((result, [a, b], index) => { |
| 30 | + result.set(a, [...(result.get(a) ?? []), [b, values[index]]]); |
| 31 | + result.set(b, [...(result.get(b) ?? []), [a, 1 / values[index]]]); |
| 32 | + return result; |
| 33 | + }, new Map()); |
| 34 | + |
| 35 | + function traverse([a, b], seen = new Set(), current = 1) { |
| 36 | + if (!map.has(a) || !map.has(b)) return -1; |
| 37 | + if (a === b) return current; |
| 38 | + seen.add(a); |
| 39 | + |
| 40 | + for (const [key, value] of map.get(a)) { |
| 41 | + if (seen.has(key)) continue; |
| 42 | + const result = traverse([key, b], seen, current * value); |
| 43 | + if (result) return result; |
| 44 | + } |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + return queries.map(item => traverse(item) ?? -1); |
| 49 | +}; |
0 commit comments