#399

Evaluate Division

specialist · 655 · lc medium +30 · verified · 64% accepted · 10,163 likes · top 67%

play →

Description

You are given an array equations and a numeric array values such that equations[i] = [Ai, Bi] encodes the relationship Ai / Bi = values[i].

For each query [Cj, Dj] in queries, derive the value of Cj / Dj from the given relationships. Return -1.0 if the answer cannot be determined (unknown variable or disconnected relationship).

The input contains no contradictions and no division-by-zero scenarios.

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]
Explanation:
Given: a / b = 2.0, b / c = 3.0
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
note: x is undefined => -1.0

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]

Example 3:

Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
Output: [0.50000,2.00000,-1.00000,-1.00000]

Code

1
2
3