You are given a list of equations of the form a / b = value, where a and b are variable names and value is a real number. From these known ratios you may derive other ratios by chaining divisions together, for example if a / b and b / c are known, then a / c is their product.
For each query of the form c / d, compute the resulting value using only the equations provided. If the answer cannot be determined, either because a variable never appears in any equation or because no chain of divisions connects the two variables, return -1.0 for that query.
Return an array holding the answer to every query in the same order the queries are given.
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]
a/c = (a/b)*(b/c) = 2*3 = 6, b/a = 1/2 = 0.5, e is unknown so a/e is -1, a/a is 1, and x never appears so x/x is -1.
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]
a/c = 1.5*2.5 = 3.75, c/b = 1/2.5 = 0.4, bc/cd is given as 5.0, and cd/bc is its reciprocal 0.2.
Constraints
1 <= equations.length <= 20equations[i].length == 21 <= Ai.length, Bi.length <= 5values.length == equations.length0.0 < values[i] <= 20.01 <= queries.length <= 20queries[i].length == 21 <= Cj.length, Dj.length <= 5Ai, Bi, Cj, Dj consist of lowercase English letters and digits.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI