DSA problem
Evaluate Division
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [A_i, B_i] and values[i] represent the equation A_i / B_i = values[i]. Each A_i or B_i is a string that represents a single variable. You are also given some queries, where queries[j] = [C_j, D_j] represents the j-th query where you must find the answer for C_j / D_j.
Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note that the input is always valid: you may assume that no contradictions arise and division by zero never occurs.
The core insight: every chain of divisions tells you the ratio of two variables. a/b = x and b/c = y together imply a/c = x * y. So we can build an undirected weighted graph where the edge a -> b carries the weight a / b, and the reverse edge b -> a carries 1 / (a / b). Answering a query u / v is then a search from u to v multiplying weights along the path.
The optimal Union-Find approach uses a "weighted DSU": each node stores its parent plus a weight that equals the ratio node / parent. find returns the root AND folds the cumulative product into the node's weight during path compression. union(a, b, k) connects the two roots with a single edge whose weight is computed so the invariant a / b = k is preserved. A query u / v returns weight[u] / weight[v] if they share a root, else -1.0. All operations are amortised O(α(n)).
Examples
equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]][6.0,0.5,-1.0,1.0,-1.0]equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]][3.75,0.4,5.0,0.2]equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]][0.5,2.0,-1.0,-1.0]Constraints
- 1 <= equations.length <= 20
- equations[i].length == 2
- 1 <= A_i.length, B_i.length <= 5
- values.length == equations.length
- 0.0 < values[i] <= 20.0
- 1 <= queries.length <= 20
- queries[i].length == 2
- 1 <= C_j.length, D_j.length <= 5
- A_i, B_i, C_j, D_j consist of lowercase English letters and digits.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.