Evaluate Division: Equations as a Weighted Graph

LeetCode 399 gives equations like a / b = 2.0 and asks for queries like a / c. The trick: each equation is a weighted edge.

Build the graph

  • For a / b = k add an edge a -> b with weight k
  • Add the reverse edge b -> a with weight 1/k
  • A query x / y is the product of weights along any path from x to y

Answer each query with DFS

  • If x or y is unknown, return -1.0
  • If x == y, return 1.0
  • Otherwise DFS from x, multiplying weights, until you reach y

Union-find alternative

  • Weighted union-find stores each node's ratio to its root, with path compression
  • x / y = ratio(x) / ratio(y) when both share a root
  • Complexity: O(Q * (V + E)) for DFS, close to O(Q) for union-find
  • Say why the reverse edge is 1/k and how you handle unknown variables

Disclosure

I work on Linkjob AI, an AI interview assistant for live technical interviews.

Made with Slides.com