Took me an embarrassingly long time to see this as a graph problem.
Model the equations as a directed graph where each variable is a node and each equation A/B = k creates two directed edges: A→B with weight k and B→A with weight 1/k. For each query C/D, perform a graph traversal (DFS or BFS) from C to D, multiplying edge weights along the path; if no path exists, return -1.0.
Pro tip: Precompute connected components and cache results for frequently queried pairs to avoid redundant traversals, and always handle edge cases like C == D (return 1.0) and division by zero (though k is real, ensure no zero weights).
Create an adjacency list where each node maps to a list of (neighbor, weight) pairs. For each equation A/B = k, add edge A→B with weight k and B→A with weight 1/k.
If C == D, return 1.0 immediately. If either C or D is not in the graph, return -1.0.
For each query C/D, perform DFS or BFS from C to D, multiplying edge weights along the path. If D is reached, return the product; otherwise, return -1.0.
Optionally, cache results for repeated queries or precompute all-pairs reachability within each connected component to speed up multiple queries.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.