Ctrl K

Ratio Chain Queries

Medium
You are given known ratios between variables: pairs[i] = [a, b] together with ratios[i] means that a / b = ratios[i]. Each variable name is a short string. You also get a list of questions asks, where asks[j] = [c, d] asks for the value of c / d. Return the answers in the order of the questions. If an answer cannot be derived from the known ratios, put -1.0 in its place. A variable that appears in no ratio is unknown, so even its ratio to itself is undefined. The data is consistent, and no division by zero will happen. Answers are compared with a tolerance of 10⁻⁶.
Example 1
pairs=[["usd", "eur"], ["eur", "gbp"]], ratios=[1.25, 1.2], asks=[["usd", "gbp"], ["gbp", "eur"], ["usd", "yen"]] → [1.5, 0.8333333333333334, -1]

usd / gbp = (usd / eur) · (eur / gbp) = 1.25 · 1.2 = 1.5; gbp / eur = 1 / 1.2 ≈ 0.8333; nothing is known about yen, so -1.0.

Example 2
pairs=[["a", "b"], ["c", "d"]], ratios=[4.0, 0.5], asks=[["a", "c"], ["d", "c"], ["b", "b"], ["z", "z"]] → [-1, 2.0, 1.0, -1]

a and c are not linked by any chain, so -1.0. d / c = 2.0. b / b = 1.0 because b appears in the data. z appears nowhere, so even z / z is unknown.

Constraints
  • 1 ≤ len(pairs) ≤ 20, len(ratios) == len(pairs)
  • 0 < ratios[i] ≤ 20
  • 1 ≤ len(asks) ≤ 20
  • Names are 1 to 5 characters long: lowercase English letters and digits
  • The ratios do not contradict each other
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBall Into the Hole HardShortest Path of a Rolling Ball MediumMerge Contact Cards MediumChains of Synonyms MediumRearrange Through Links Medium
loading Python…
Input
pairs=[["usd", "eur"], ["eur", "gbp"]], ratios=[1.25, 1.2], asks=[["usd", "gbp"], ["gbp", "eur"], ["usd", "yen"]]
Expected
[1.5, 0.8333333333333334, -1]

Run checks the first 3 tests in your browser. Submit checks all 37 tests on the server, hidden ones included.