Evaluate Division

Medium#399graph

You get equations of the form x / y = k between variables, and queries x / y. Answer each query from the equations, or with -1 if they say nothing about it (a variable no equation names, or two variables no chain of equations links). Our equations: p / r = 5, r / u = 0.5, r / s = 4; queries: p / s, s / p, p / q. The answers are [20, 0.05, -1].

input
equations and values: equations equations[i][0] / equations[i][1] = values[i] between variables named by strings; queries: pairs of variables [c, d].
returns
For each query the value of c / d that follows from the equations, or -1.0 if it does not follow: the two are not linked by equations, or a variable is in none of them (x / x too).
constraints
  • 1 ≤ equations.length ≤ 20
  • values.length = equations.length
  • 0 < values[i] ≤ 20
  • 1 ≤ queries.length ≤ 20
  • equations[i], queries[j]: pairs of names of 1–5 lowercase letters and digits
  • the equations do not contradict each other
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string[][]} equations
 * @param {number[]} values
 * @param {string[][]} queries
 * @return {number[]}
 */
function calcEquation(equations, values, queries) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.