Evaluate Division (LeetCode 399): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Union Find
Graph
Shortest Path

You are told the values of several ratios like a / b = 2.0 and then asked about other ratios between the same variables. Return each queried ratio if it can be derived from the given equations, or -1.0 if it cannot.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Think about what a / c means when you only know a / b and b / c. Multiplying them cancels b, so a / c = (a / b) × (b / c). Any chain of known ratios that starts at the numerator and ends at the denominator works the same way, because the intermediate variables cancel out.

That makes a graph the right model. Each variable is a node. An equation a / b = v gives an edge from a to b with weight v and an edge from b to a with weight 1 / v. A query x / y is then a path search from x to y, and the answer is the product of the weights along any path. Any path gives the same value because the equations are guaranteed to be consistent, so you do not need the shortest one.

Two special cases follow from the graph. If either variable never appeared in an equation, it is not in the graph and the answer is -1.0, even for something like x / x. If a variable is known, dividing it by itself is 1.0. Everything else is a BFS that carries a running product, multiplying in each edge weight as it moves outward.

Approach: Weighted graph with BFS per query

  1. Build graph as a map from each variable to a map of neighbors and weights.
  2. For each equation (a, b) with value val, set graph[a][b] = val and graph[b][a] = 1.0 / val.
  3. For a query (src, dst), return -1.0 if either is missing from the graph, and 1.0 if src == dst.
  4. Otherwise BFS from src with a queue of (node, product) pairs, starting from (src, 1.0).
  5. When a popped node equals dst, return its product; otherwise push each unvisited neighbor with product * weight.
  6. If the queue empties, the variables are in different components, so return -1.0.

Step-by-step example

equations = [["a","b"],["b","c"]], values = [2.0, 3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
  1. The graph has a to b with weight 2, b to a with 0.5, b to c with 3 and c to b with 1 / 3.
  2. Query a / c: BFS pops a, pushes b with product 2. Popping b pushes c with 2 × 3 = 6. Popping c matches the target, so the answer is 6.0.
  3. Query b / a: from b, the neighbor a is pushed with product 0.5 and returned when popped, giving 0.5.
  4. Query a / e: e is not in the graph, so the answer is -1.0. Query a / a: a exists and equals itself, so 1.0.
  5. Query x / x: x never appeared, so the answer is -1.0. The output is [6.0, 0.5, -1.0, 1.0, -1.0].

Code: Python, Java, C++

1class Solution:
2    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
3        graph = defaultdict(dict)
4
5        # Build graph
6        for (a, b), val in zip(equations, values):
7            graph[a][b] = val
8            graph[b][a] = 1.0 / val
9
10        def bfs(src, dst):
11            if src not in graph or dst not in graph:
12                return -1.0
13            if src == dst:
14                return 1.0
15
16            visited = set([src])
17            queue = [(src, 1.0)]
18
19            while queue:
20                node, prod = queue.pop(0)
21                if node == dst:
22                    return prod
23                for neighbor, weight in graph[node].items():
24                    if neighbor not in visited:
25                        visited.add(neighbor)
26                        queue.append((neighbor, prod * weight))
27            return -1.0
28
29        return [bfs(a, b) for a, b in queries]

Time and space complexity

Time

O(Q × (V + E))

Each of the Q queries can run a BFS that touches every variable and every equation edge.

Space

O(V + E)

The graph stores two directed edges per equation, and each BFS uses a visited set and queue of at most V entries.

Other approaches

Weighted union-find (time O((E + Q) × α(V)), space O(V))

Store each variable's ratio to its root and merge sets with the right weight. A query is answered by comparing ratios to a shared root, which is nearly constant time per query.

Floyd-Warshall precomputation (time O(V³ + Q), space O(V²))

Fill a table of ratios for every pair of variables with a triple loop, then answer each query by lookup. Good when there are many queries and few variables.

Common mistakes

  • Returning 1.0 for x / x when x never appeared in any equation; the correct answer is -1.0.
  • Adding only the forward edge a to b, which makes queries like b / a unreachable.
  • Marking nodes as visited when popped instead of when pushed lets the same node enter the queue several times on graphs with cycles.
  • Summing weights along the path instead of multiplying them; ratios combine by multiplication.

Frequently asked questions

Why model evaluate division as a graph?

A known ratio links two variables, and chaining ratios multiplies them while the middle variables cancel. Finding a chain from the numerator to the denominator is a path search.

Why is the reverse edge weight 1 / value?

If a / b = v, then b / a = 1 / v. Adding both directions lets any query find a path regardless of which way the equations were written.

What if the two variables are in different components?

Then no chain of equations connects them, the BFS exhausts its queue without reaching the target, and the answer is -1.0.

Is union-find better than BFS here?

With few queries BFS is simpler. With many queries, weighted union-find answers each one in nearly constant time instead of a full graph search.