mediumGraphBFSGraphs

Evaluate Division

mediumTime: 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.

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.

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