Compute Division Chains from Given Ratios
Trees & GraphsAuto-graded · 13 test casesLast updated
Tests graph modeling of multiplicative relationships and pathfinding to derive transitive ratios between variables.
You receive a collection of ratio relationships and must answer queries about derived ratios.
You are given:
equations: a list of pairs whereequations[i] = [X, Y]means you know the value ofX / Yvalues: a list of numbers wherevalues[i]is the numeric result ofequations[i][0] / equations[i][1]queries: a list of pairs wherequeries[j] = [P, Q]asks you to computeP / Q
Return a list of answers, one per query. For each query [P, Q]:
- If you can determine
P / Qfrom the given equations, return that ratio as a float - If you cannot determine the ratio (because a variable is unknown or unreachable), return
-1.0
Important rules:
- Variables are strings
- A variable is "known" only if it appears in at least one equation
- For a known variable
X, the ratioX / Xequals1.0 - For an unknown variable
Y, evenY / Yreturns-1.0 - All given ratios are positive and the system is consistent
Constraints
1 <= equations.length <= 20equations[i].length == 21 <= equations[i][0].length, equations[i][1].length <= 5values.length == equations.length0.0 < values[i] <= 20.01 <= queries.length <= 20queries[j].length == 21 <= queries[j][0].length, queries[j][1].length <= 5
Examples
Example 1
Input: compute_division_queries([['a', 'b'], ['b', 'c']], [2, 3], [['a', 'c'], ['b', 'a'], ['a', 'e']])
Output: [6, 0.5, -1]
Hints
Hint 1
Model each variable as a node in a graph. What edge structure lets you compute ratios by following paths?
Hint 2
If you know A/B = k, you also know B/A = 1/k. How does this affect your graph?
Hint 3
Use BFS or DFS from the numerator. Track the accumulated product of edge weights as you traverse toward the denominator.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to represent the problem as a weighted directed graph where variables are nodes and ratio relationships are edges.
For each equation X / Y = k, we create two directed edges:
- An edge from
XtoYwith weightk(representingX / Y = k) - An edge from
YtoXwith weight1/k(representingY / X = 1/k)
To answer a query P / Q, we search for any path from node P to node Q. If such a path exists, the answer is the product of all edge weights along that path. This works because:
P / Q = (P / intermediate₁) × (intermediate₁ / intermediate₂) × ... × (intermediateₙ / Q)
The intermediate terms cancel out, leaving us with P / Q.
We use breadth-first search (BFS) starting from P, tracking the accumulated ratio as we explore. Each time we visit a node current with accumulated ratio r, we know that P / current = r. When we reach Q, the accumulated ratio is our answer.
Special cases:
- If either variable doesn't appear in any equation, return
-1.0 - If both variables are the same and the variable is known, return
1.0 - If no path exists between the variables, return
-1.0
Why It Works
The graph construction captures all direct and inverse relationships. Since the input is consistent (no contradictions), any path between two nodes yields the same product. BFS finds a path if one exists, and the visited set prevents infinite loops caused by cycles.
The critical ordering is checking variable existence before checking self-equality, ensuring that X / X returns -1.0 for unknown X but 1.0 for known X.
Complexity
Let V be the number of distinct variables and E be the number of equations.
Time Complexity: O(E + Q × (V + E))
- Building the graph:
O(E) - Each query performs BFS:
O(V + E)to visit all reachable nodes and edges - Total for
Qqueries:O(Q × (V + E))
Space Complexity: O(V + E)
- Graph storage:
O(E)edges across all adjacency lists - Per-query:
O(V)for the queue and visited set
With the given constraints (at most 20 equations and 20 queries), this is highly efficient.
from collections import defaultdict, deque
from typing import List
def compute_division_queries(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
# Build bidirectional weighted graph where edge x->y has weight x/y
graph = defaultdict(list)
for (numerator, denominator), ratio in zip(equations, values):
graph[numerator].append((denominator, ratio))
graph[denominator].append((numerator, 1.0 / ratio))
results = []
for source, destination in queries:
# Check if both variables exist in our equations
if source not in graph or destination not in graph:
results.append(-1.0)
continue
# Self-division for known variables
if source == destination:
results.append(1.0)
continue
# BFS to find path and accumulate ratio
queue = deque([(source, 1.0)])
visited = {source}
answer = -1.0
while queue:
current, accumulated = queue.popleft()
for next_node, edge_weight in graph[current]:
if next_node in visited:
continue
new_accumulated = accumulated * edge_weight
if next_node == destination:
answer = new_accumulated
queue.clear()
break
visited.add(next_node)
queue.append((next_node, new_accumulated))
results.append(float(answer))
return results