Problem Statement

Evaluate Division

You are told some facts like a/b = 2.0, which means a is 2 times bigger than b. Then you get questions like "what is a/c?" and you have to figure out the answer using the facts you have. The trick is to picture the facts as a map. Each letter is a place, and each fact is a road between two places with a number on it. If you can walk from the starting letter to the ending letter, you multiply the numbers along the road to get the answer. This kind of map is called a graph: a set of points (called nodes) connected by lines (called edges). Here the edges are weighted, meaning each line carries a number. Because a/b = k also tells us b/a = 1/k, every road runs both ways: forward with weight k, backward with weight 1/k.

mediumGraphBFSGraphsTime: O(Q * (V+E)) · Space: O(V+E)

Signals to notice

evaluate equations a/b given as graph edgespath finding gives ratiosweighted graph

Brute force first

For each query, try all paths — potentially exponential without visited tracking. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Build a weighted directed graph: a/b = v means edge a→b with weight v and b→a with weight 1/v. For each query, BFS/DFS from start to end, multiplying weights along the path. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on equations=[["a","b"],["b","c"]], values=[2.0,3.0], query=["a","c"]

Build graph: a→b=2.0, b→a=0.5, b→c=3.0, c→b=0.333
bfs(a,c): both in graph, a!=c → queue=[(a,1.0)], visited={a}
pop (a,1.0): scan a's edges → b (weight 2.0)
b != dst c → enqueue (b, 1.0*2.0=2.0), visited={a,b}
pop (b,2.0): scan b's edges → a (visited, skip), then c (weight 3.0)
c == dst → return prod*weight = 2.0*3.0 = 6.0
Answer for query [a,c] = 6.0

What must stay true

If a/b = 2 and b/c = 3, then a/c = 6. The path from a to c in the graph gives the product of edge weights, which is the division result. No path means undefined (-1). If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

build graph: for each a/b=v, add edge a→b=v and b→a=1/v
bfs(src, dst): if src or dst not in graph → -1; if src==dst → 1
  queue = [(src, 1.0)]; visited = {src}
  pop (node, prod); for (nei, w) in graph[node]:
    if nei==dst → return prod*w; else enqueue (nei, prod*w) if unvisited
  return -1   # no path

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not adding the reverse edge — if a/b = 2, then b/a = 0.5. Both directions must be in the graph. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Graphs Pattern