Evaluate Division solution explained
Evaluate Division is a graph problem in disguise: each equation a / b = v becomes an edge from a to b with weight v and an edge back with weight 1 / v, and a query x / y is the product of the weights along any path from x to y. Answer each query with a BFS or DFS that multiplies as it goes, or build a weighted union-find in which every variable stores its ratio to its group's root, so that x / y is just ratio(x) divided by ratio(y). Unknown variables and variables in different groups give -1.
By Evin JohnPublished 8 min read
Restating the problem
You get a list of equations, each naming two variables and a positive number: a / b = v. Then you get queries, each naming two variables x and y. For each query, return the value of x / y implied by the equations, or -1.0 if the equations do not determine it. Assume the equations never contradict each other and no value is zero.
| Query | Answer | Reasoning |
|---|---|---|
| p / r | 32 | p / q times q / r = 2 × 16 |
| r / p | 0.03125 | The reciprocal, 1 / 32 |
| s / t | 3 | Given directly |
| p / s | -1 | p and s are in separate groups, nothing links them |
| t / t | 1 | t appears in an equation, so it is known to equal itself |
| u / u | -1 | u never appears, so nothing is known about it |
What it checks
The story is about division, and candidates who stay in algebra get stuck. The interviewer is looking for the moment you see a graph: variables are nodes, each equation gives two directed edges, and following a path multiplies ratios. After that it is a search problem. The strongest answers also handle the two odd cases without prompting, an unknown variable and a variable divided by itself, and know the union-find upgrade for many queries.
Graph search per query
Build an adjacency list where each edge carries its weight. For a query x / y, start a BFS at x with a ratio of 1. When you move from a node to a neighbour along an edge of weight w, the neighbour's ratio is the current ratio times w, which keeps the meaning "x divided by this node". Stop when y gets a ratio or the queue empties. If either name is missing from the graph, answer -1 straight away; that check is also what makes u / u come out as -1 and t / t as 1.
from collections import defaultdict, deque
def calc_equation_bfs(equations, values, queries):
graph = defaultdict(list)
for (a, b), v in zip(equations, values):
graph[a].append((b, v)) # a / b = v
graph[b].append((a, 1.0 / v)) # b / a = 1 / v
answers = []
for start, goal in queries:
if start not in graph or goal not in graph:
answers.append(-1.0)
continue
ratio = {start: 1.0} # ratio[x] = start / x
queue = deque([start])
while queue and goal not in ratio:
node = queue.popleft()
for nxt, v in graph[node]:
if nxt not in ratio:
ratio[nxt] = ratio[node] * v
queue.append(nxt)
answers.append(ratio.get(goal, -1.0))
return answersTrace p / r. The BFS starts with ratio[p] = 1. The edge p to q has weight 2, so ratio[q] = 2, meaning p / q = 2. The edge q to r has weight 16, so ratio[r] = 32, and the loop stops because the goal now has a ratio. DFS works the same way; BFS avoids deep recursion on long chains.
Weighted union-find
If there are many queries, re-searching the graph each time is wasteful. Union-find groups the variables that are connected, and a small addition makes it carry ratios: each variable stores its parent and weight = variable / parent. Following parents to the root and multiplying the weights gives variable / root. Two variables in the same group then divide cleanly: x / y = (x / root) / (y / root).
To union a / b = v, find both roots. After path compression, weight[a] = a / ra and weight[b] = b / rb. Attach ra under rb with weight ra / rb, which works out to v × weight[b] / weight[a]. The find below is iterative and compresses the path as it returns, fixing the weights from the node nearest the root outward, so each node's weight is relative to the root once it is done.
def calc_equation(equations, values, queries):
parent, weight = {}, {} # weight[x] = x / parent[x]
def find(x):
path = []
while parent[x] != x:
path.append(x)
x = parent[x]
for node in reversed(path): # nearest the root first
if parent[node] != x:
weight[node] *= weight[parent[node]]
parent[node] = x
return x # now weight[node] = node / root
for (a, b), v in zip(equations, values):
for name in (a, b):
if name not in parent:
parent[name], weight[name] = name, 1.0
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
weight[ra] = v * weight[b] / weight[a] # ra / rb
answers = []
for a, b in queries:
if a not in parent or b not in parent or find(a) != find(b):
answers.append(-1.0)
else:
answers.append(weight[a] / weight[b])
return answersfunction calcEquation(equations, values, queries) {
const parent = new Map();
const weight = new Map(); // weight of x = x / parent of x
function find(x) {
const path = [];
while (parent.get(x) !== x) {
path.push(x);
x = parent.get(x);
}
for (let i = path.length - 1; i >= 0; i--) {
const node = path[i];
const up = parent.get(node);
if (up !== x) weight.set(node, weight.get(node) * weight.get(up));
parent.set(node, x);
}
return x;
}
equations.forEach(([a, b], i) => {
for (const name of [a, b]) {
if (!parent.has(name)) {
parent.set(name, name);
weight.set(name, 1);
}
}
const ra = find(a);
const rb = find(b);
if (ra !== rb) {
parent.set(ra, rb);
weight.set(ra, (values[i] * weight.get(b)) / weight.get(a));
}
});
return queries.map(([a, b]) => {
if (!parent.has(a) || !parent.has(b) || find(a) !== find(b)) return -1;
return weight.get(a) / weight.get(b);
});
}The order inside find matters. The path is walked from the start node up, but the weights must be fixed from the top down: a node's new weight is its old weight times its parent's weight, and that is only correct once the parent's weight already points at the root. Processing the path in reverse does exactly that.
Complexity
| Approach | Build | Per query | Space |
|---|---|---|---|
| BFS or DFS per query | O(V + E) | O(V + E) | O(V + E) |
| Weighted union-find, path compression only | O(E log V) worst case | O(log V) amortized worst case | O(V) |
| Union-find with union by size as well | O(E · α(V)) | O(α(V)) | O(V) |
| Precompute every pair (Floyd-Warshall style) | O(V³) | O(1) | O(V²) |
The code above uses path compression only, which is already fast in practice and the version most candidates write. Adding union by size, attaching the smaller group under the larger, brings the bound down to α(V). Mention it, then write the short version unless asked.
Edge cases
- A variable that appears in no equation, including x / x for that variable: -1.
- A known variable divided by itself: 1.
- Two variables that exist but sit in different groups: -1.
- The same pair given twice, or a pair given in both directions. Consistent input means the second one adds nothing.
- Very long chains, where recursive DFS can hit Python's recursion limit. BFS or an iterative find avoids that.
- Floating-point drift after many multiplications. Answers are usually compared with a tolerance; say so.
Mistakes
- Adding only the a to b edge and forgetting the reverse edge with weight 1 / v.
- Returning 1 for x / x without checking that x exists.
- In union-find, attaching a to b instead of root to root, which loses the rest of a's group.
- Computing the new root weight before calling find, so the weights are not yet relative to the roots.
- Fixing path weights from the bottom up during compression.
- Not marking nodes as visited in the search, which loops forever on the two-way edges.
How to explain it out loud
Fictional example
- Candidate
- If p over q is 2 and q over r is 16, then p over r is the product along the chain. So I'll make each variable a node, with an edge p to q of weight 2 and q to p of weight one half.
- Candidate
- A query is a path search that multiplies weights. If either variable is missing, or no path exists, the answer is minus one.
- Interviewer
- What if there are a hundred thousand queries?
- Candidate
- Then I'd use union-find where each node stores its ratio to the root. x over y becomes the ratio of x divided by the ratio of y, after one find each, which is close to constant time.
Related problems
Union-find shows up again in Accounts Merge, without weights, and in Swim in Rising Water as one of the ways to connect cells. For plain connected components on a grid, see Number of Islands. The prefix sum pattern is the same idea in one dimension: store each element relative to a fixed origin, then answer any pair by one division or subtraction.
Studying it with Natively
The weighted union-find is a lot to hold in your head on a first attempt. Natively can read the problem from a screenshot on Mac or Windows and put a worked approach and code in its overlay, which you can follow line by line against your own find function. In a spoken mock, its transcript shows afterwards whether you explained the reverse edge and the unknown-variable case. See the AI interview assistant.
Questions people ask
How do you solve Evaluate Division?
Treat each variable as a node and each equation a / b = v as an edge a to b with weight v and b to a with weight 1 / v. A query x / y is the product of weights on a path from x to y, or -1 if there is no path.
Why is Evaluate Division a graph problem?
Dividing along a chain multiplies ratios: a / c equals a / b times b / c. Following edges and multiplying their weights does exactly that.
How does weighted union-find work for Evaluate Division?
Each variable stores its parent and its value divided by its parent's. After path compression, every variable holds its ratio to the root, so x / y is ratio(x) divided by ratio(y) when they share a root.
What should x / x return in Evaluate Division?
1 if x appears in at least one equation, and -1 if it never appears, because nothing is known about an unknown variable.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
