InterviewPrepKit

Home / Coding / Graphs

Evaluate Division

medium Original ↗
Solving tips
  • Model each fact a/b=k as a weighted graph with edge a->b weight k AND the reverse b->a weight 1/k; then x/y is the product of edge weights along any path from x to y.
  • For each query DFS/BFS from x carrying the running product; return -1.0 if x or y is unknown or no path connects them. This is O(V+E) per query.
  • Pitfall: x/x is 1.0 only if x actually appears in the equations; an unknown variable (even x/x) must return -1.0.
  • For many queries against fixed equations, weighted union-find storing each node's ratio to its component root gives near-O(1) queries after an O(E*alpha) build.

Problem

You’re given a list of equations like ["a", "b"] paired with values like 2.0, meaning a / b = 2.0. Each variable is a string.

For each query ["x", "y"], return the value of x / y deduced from the given facts, or -1.0 if it can’t be determined. A query is undeterminable when a variable never appears in any equation, or when x and y sit in disconnected groups. x / x is 1.0 only if x appears somewhere in the equations.

All given values are positive, so no division by zero occurs.

Examples

  • Equations [["a","b"],["b","c"]], values [2.0, 3.0], queries [["a","c"],["b","a"],["a","e"],["x","x"]][6.0, 0.5, -1.0, -1.0].
    • a/c = a/b · b/c = 2·3 = 6; b/a = 1/(a/b) = 0.5; e is unknown → -1; x never appears → -1.
  • Equations [["a","b"]], values [0.5], queries [["a","b"],["b","a"],["a","a"],["c","c"]][0.5, 2.0, 1.0, -1.0].
    • a/a = 1 (a is known); c/c = -1 (c is unknown).

Constraints

  • 1 <= len(equations) <= 20, and up to 20 queries.
  • Each variable string has length 1..5, lowercase letters/digits.
  • All values are in (0.0, 20.0]; the given equations are internally consistent.

Think about it first

Hint 1 Treat each variable as a node. The fact a / b = k is a directed edge a → b with weight k, and the reverse edge b → a with weight 1/k. Then x / y is the product of edge weights along any path from x to y.
Hint 2 For a query, run a graph traversal (DFS or BFS) from x, carrying the running product. If you reach y, that product is the answer. If x or y isn't a node, or no path exists, return -1.0.
Hint 3 Because the ratios are consistent, all variables in a connected component share a common reference. Weighted union-find exploits this: store each node's ratio to its component root, so a query becomes a near-O(1) comparison of two nodes' ratios once they share a root.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.