AlgoInsight

DSA problem

Evaluate Division

MediumUnion FindPattern: Union Findtop600AmazonGoogleMicrosoftBloombergUber

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

Example 1
Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.0,0.5,-1.0,1.0,-1.0]
Explanation: a/c = (a/b) * (b/c) = 2 * 3 = 6. b/a = 1 / (a/b) = 0.5. a/e is unknown (e is undefined). a/a = 1. x/x is undefined because x was never seen.
Example 2
Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
Output: [3.75,0.4,5.0,0.2]
Explanation: a/c = 1.5 * 2.5 = 3.75. c/b = 1/2.5 = 0.4. bc/cd = 5.0. cd/bc = 1/5.0 = 0.2.
Example 3
Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
Output: [0.5,2.0,-1.0,-1.0]
Explanation: Only one equation; queries about unknown variables return -1.0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

graphunion-findweighted-dsudfshash-map

Browse all DSA problems