InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Evaluate Division

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug