Evaluate Division

Compute `a / d` from given pairwise ratios — DFS over the ratio graph (or weighted Union-Find).

Medium
Time O((E + Q) * V) Space O(V)
LeetCode
6 min read
union-find graph dfs

Problem#

Given equations [A, B] with values A / B = v, evaluate the queries. Each query [X, Y] should return X / Y, or -1.0 if undetermined.

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].

Constraints#

  • 1 <= equations.length, queries.length <= 20.

Hints#

Hint
Model each variable as a node; each equation gives bidirectional weighted edges A -> B (value v) and B -> A (1/v). DFS multiplies edge weights.

Approach#

Build a directed-weighted graph: g[A][B] = v and g[B][A] = 1/v. For each query, DFS from X looking for Y, multiplying weights along the path. Return -1.0 if either node is missing or Y is unreachable.

Solution#

Evaluate Division
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values,
vector<vector<string>>& queries) {
unordered_map<string, unordered_map<string,double>> g;
for (int i = 0; i < (int)equations.size(); ++i) {
const string& a = equations[i][0];
const string& b = equations[i][1];
g[a][b] = values[i];
g[b][a] = 1.0 / values[i];
}
auto query = [&](const string& src, const string& dst) -> double {
if (!g.count(src) || !g.count(dst)) return -1.0;
if (src == dst) return 1.0;
unordered_set<string> seen{src};
function<double(const string&, double)> dfs = [&](const string& node, double acc) -> double {
if (node == dst) return acc;
for (auto& [nx, w] : g[node]) {
if (seen.insert(nx).second) {
double r = dfs(nx, acc * w);
if (r >= 0) return r;
}
}
return -1.0;
};
return dfs(src, 1.0);
};
vector<double> ans;
ans.reserve(queries.size());
for (auto& q : queries) ans.push_back(query(q[0], q[1]));
return ans;
}
};

Editorial#

Each equation is a multiplicative edge — a / b = v translates to “moving from a to b multiplies the running ratio by v.” DFS from source to destination accumulates the product. Weighted Union-Find is an alternative offering O(α) queries by storing weight[v] as ratio to root, but DFS is simpler for the problem’s small size.

Complexity#

  • Time: O((E + Q) * V).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.