30 · Advanced Graphs: Euler Paths, Bridges & SCCs

#399 Evaluate Division

Mediumsolve on LeetCode ↗

frequently reported atUberBloombergAmazonGoogleMeta

the problem

In plain words

You get facts of the form a / b = k: equations[i] = [a, b] with the value values[i]. Variable names are short strings of lowercase letters and digits. For each query [c, d], work out c / d from the facts. If it can't be worked out — for example, a variable never appears in any fact — answer -1.0. The facts never contradict each other and never divide by zero.

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

out [6.0,0.5,-1.0,1.0,-1.0]

a / c = (a / b) · (b / c) = 2 · 3. b / a = 1 / 2. e and x appear in no equation.

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

out [3.75,0.4,5.0,0.2]

in equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]

out [0.5,2.0,-1.0,-1.0]

  • 1 ≤ equations.length ≤ 20, values.length == equations.length
  • 0.0 < values[i] ≤ 20.0
  • 1 ≤ queries.length ≤ 20
  • Names have 1–5 lowercase letters or digits

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #1514
      Path with Maximum Probability
      Mediumin Shortest Paths
    2. #990
      Satisfiability of Equality Equations
      Mediumin Union-Find & MST
    3. #721
      Accounts Merge
      Mediumin Union-Find & MST