780. Ratio Queries

A restoration workshop keeps a ledger of how fast pairs of pulleys turn. Entry i says that pulley equations[i][0] turns values[i] times as fast as pulley equations[i][1]. Speeds are always positive and the ledger never contradicts itself.

Each query [x, y] asks how many times faster pulley x turns than pulley y, using only what the ledger lets you chain together. Return a double[] with one answer per query, in query order. If either pulley never appears in the ledger, or the two are not linked by any chain of entries, the answer is -1.0 (this includes an unknown pulley compared with itself). A pulley from the ledger compared with itself gives 1.0. Answers within 1e-6 are accepted.

Example 1

Input:
equations = [["rotor","gear"],["gear","cog"]]values = [2,3]queries = [["rotor","cog"],["cog","rotor"],["gear","gear"],["rotor","belt"]]
Output:
[6,0.16666666666666666,1,-1]
Explanation:

Rotor is 2 times gear and gear is 3 times cog, so rotor is 6 times cog and cog is 1/6 of rotor; gear against itself is 1; belt is not in the ledger, so -1.

Example 2

Input:
equations = [["p","q"],["r","s"]]values = [0.5,4]queries = [["q","p"],["p","s"],["s","r"],["p","p"],["z","z"]]
Output:
[2,-1,0.25,1,-1]
Explanation:

q turns twice as fast as p, s is a quarter of r, p and s lie in separate chains so that answer is -1, p against p is 1, and z never appears so even z against z is -1.

Constraints

  • 1 ≤ equations.length = values.length ≤ 105
  • 1 ≤ queries.length ≤ 105
  • Names are 1 to 10 characters, lowercase letters and digits
  • 10-9 ≤ values[i] ≤ 109, and every answerable query has an answer in the same range
  • The ledger is consistent: all chains between two pulleys give the same ratio

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(E + Q)
Space
O(E)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…