MediumArrayDepth-First SearchUnion FindGraphShortest Path

1 approach, code in every language

Problem description

You are given a list of equations of the form a / b = value, where a and b are variable names and value is a real number. From these known ratios you may derive other ratios by chaining divisions together, for example if a / b and b / c are known, then a / c is their product.

For each query of the form c / d, compute the resulting value using only the equations provided. If the answer cannot be determined, either because a variable never appears in any equation or because no chain of divisions connects the two variables, return -1.0 for that query.

Return an array holding the answer to every query in the same order the queries are given.

Example 1

Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]

Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]

a/c = (a/b)*(b/c) = 2*3 = 6, b/a = 1/2 = 0.5, e is unknown so a/e is -1, a/a is 1, and x never appears so x/x is -1.

Example 2

Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]

Output: [3.75000,0.40000,5.00000,0.20000]

a/c = 1.5*2.5 = 3.75, c/b = 1/2.5 = 0.4, bc/cd is given as 5.0, and cd/bc is its reciprocal 0.2.

Constraints

  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • 1 <= Ai.length, Bi.length <= 5
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • 1 <= queries.length <= 20
  • queries[i].length == 2
  • 1 <= Cj.length, Dj.length <= 5
  • Ai, Bi, Cj, Dj consist of lowercase English letters and digits.

After the pattern

Now solve one you haven't seen.

Gear Train Ratios is our own problem on the technique behind Evaluate Division: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free