Skip to content
Decoder

Evaluate Division

Medium

Problem

You get equations like a / b = 2.0: equations[i] = [a, b] with values[i] as the result, where every name stands for a positive number. Then for each query [c, d], return the value of c / d if the equations determine it, or -1.0 if they do not (including when a name never appears in any equation). Return all answers in query order.

Example 1

equations = [["a", "b"], ["b", "c"]], values = [2.0, 3.0]

Example 2

queries   = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]

Example 3

  →  [6.0, 0.5, -1.0, 1.0, -1.0]

Example 4

  (a/c = a/b · b/c = 6, and "x" is unknown, so even x/x is -1)

Constraints

  • 1 <= equations.length <= 20
  • 1 <= queries.length <= 20
  • 0.0 < values[i] <= 20.0
  • The equations never contradict each other

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.