Evaluate Division
You are given equations of the form a / b = value, meaning variable a divided by variable b equals value. For each query x / y, return the computed value if it can be derived by chaining known equations, otherwise return -1.0. Queries involving a variable never seen in any equation also return -1.0.
Open official problem prompt ↗Answer division queries between variables using only the ratios given by a handful of known equations.
Currency exchange: if 1 dollar = 2 euros and 1 euro = 3 pesos, then dollars-to-pesos is 2*3 = 6. Chain the conversion rates along a path, and going backward uses the reciprocal rate.
- Input
- equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
- Output
- [6.0, 0.5, -1.0, 1.0, -1.0]
- Why
- a/c = (a/b)*(b/c) = 2*3 = 6; b/a = 1/2 = 0.5; e is unknown so -1; a/a = 1; x never appears so -1.
1 <= equations.length <= 20equations[i].length == 21 <= queries.length <= 20values[i] > 0.0 and 0.0 < values[i] <= 20.0Variables are strings of 1-5 lowercase letters