Took me an embarrassingly long time to stop thinking about it as algebra and realize it's just a weighted directed graph where each equation is an edge.
Model the equations as a weighted directed graph where each variable is a node and each equation A / B = k creates edges A→B with weight k and B→A with weight 1/k. For each query, perform a graph traversal (DFS or BFS) from the numerator to the denominator, multiplying edge weights along the path; if no path exists, return -1.0.
Pro tip: During traversal, cache results for visited nodes or use union-find with weights to optimize multiple queries, and always handle edge cases like unknown variables or self-division (C / C = 1.0) explicitly.
Create an adjacency list where each node is a variable. For each equation A / B = k, add a directed edge from A to B with weight k, and from B to A with weight 1/k.
For a query C / D, if either C or D is not in the graph, return -1.0. If C equals D, return 1.0. Otherwise, perform a DFS or BFS from C to D.
During traversal, keep track of the cumulative product of edge weights. When D is reached, return the product; if traversal ends without reaching D, return -1.0.
If there are many queries, consider caching results for visited node pairs or using union-find with weights to answer queries in near-constant time after preprocessing.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.