Batch Ratio Lookup Over Linked Quantities
Trees & GraphsAuto-graded · 15 test casesLast updated
Answer many ratio queries between named quantities from pairwise ratio facts, using a weighted union-find or component precomputation instead of a search per query.
Batch Ratio Lookup Over Linked Quantities
Several named quantities are related by pairwise ratio facts. Fact number i involves the pair pairs[i] = [a, b] and the number factors[i], and it says that the quantity a is factors[i] times the quantity b, that is, a / b = factors[i]. Each name stands for some unknown positive real number.
You are then given a list asks of questions [c, d]. For each one, report the value of c / d if the facts determine it, and -1.0 otherwise.
Implement the function so that it handles a large batch of questions in a single call.
Rules
- A fact can be used in both directions. If
a / b = v, thenb / a = 1 / v. c / dis determined whencanddare joined by a chain of one or more facts, each sharing a name with the next. Its value is the product of the ratios along the chain, with each fact used in the direction that fits. All chains between the same two names give the same value, because the facts never contradict each other.- If
cordappears in no fact at all, the answer is-1.0. This holds even whenc == d. - If
c == dand that name appears in at least one fact, the answer is1.0. - If both names appear in facts but no chain joins them, the answer is
-1.0. - Return exactly one answer per question, in the same order as
asks. - Every determined ratio is positive, so
-1.0can never be confused with a real answer. A determined answer is accepted if its relative error is at most1e-5. The value-1.0must be returned exactly.
Constraints
1 <= len(pairs) == len(factors) <= 1000001 <= len(asks) <= 100000len(pairs[i]) == 2andlen(asks[j]) == 2- Every name has 1 to 5 characters, each a lowercase letter or a digit.
- In each fact, the two names differ.
0.001 <= factors[i] <= 1000.0- The facts are consistent: two chains between the same pair of names never imply different ratios.
- For any two names joined by a chain, the ratio between them lies between
1e-9and1e9, so no product along a chain overflows or underflows. - Names in
asksmay be names that appear in no fact.
Examples
Example 1
Input: batch_ratio_lookup([['x', 'y'], ['y', 'z']], [4, 2.5], [['x', 'z'], ['z', 'x'], ['y', 'x'], ['x', 'w'], ['y', 'y'], ['w', 'w']])
Output: [10, 0.1, 0.25, -1, 1, -1]
Example 2
Input: batch_ratio_lookup([['p', 'q'], ['r', 's'], ['t', 'q']], [0.5, 8, 0.25], [['p', 't'], ['t', 'p'], ['p', 's'], ['s', 'r']])
Output: [2, 0.5, -1, 0.125]
Hints
Hint 1
Treat each name as a node and each fact as an edge that carries a ratio. Running a fresh search for every question is far too slow when there are 100,000 of them, so aim to do the heavy work once.
Hint 2
Within one connected group, you can express every name as a multiple of a single representative name. Then any ratio inside the group is just one stored number divided by another. A union-find structure that stores each node's ratio to its parent can maintain this.
Hint 3
When merging two groups through a fact a / b = v, work out the ratio between the two roots from each name's ratio to its root. Keep path compression iterative, since a chain of 100,000 facts will overflow Python's recursion limit. Check that both names are known before calling find.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of the names as nodes and each fact a / b = v as an edge carrying a ratio. A question c / d is the product of the edge ratios along any path from c to d, and it is unknown when no path exists.
Searching the graph separately for every question costs O(V + E) each, which is about 10^10 steps in the worst case here. Instead, build a structure once and answer each question in nearly constant time. A weighted union-find does this.
For every name x we store:
parent[x]: another name in the same group (orxitself if it is the root).ratio[x]: the value ofx / parent[x].
After find(x) has compressed the path, parent[x] is the group's root r and ratio[x] = x / r. For two names c and d with the same root:
c / d = (c / r) / (d / r) = ratio[c] / ratio[d]
So a question costs two find calls and one division.
Adding a fact a / b = v
- Register
aandbas their own roots with ratio1.0if they are new. - Compute
ra = find(a)andrb = find(b). Nowa = ratio[a] * raandb = ratio[b] * rb. - If
ra == rb, the names are already linked, and consistency means the fact adds nothing. - Otherwise attach
raunderrb. Froma / b = vwe getra / rb = v * ratio[b] / ratio[a], and that value becomesratio[ra].
Iterative find with path compression
Walk from x up to the root, recording the nodes passed. Then go back over the recorded nodes, starting with the one nearest the root. Keep a running product of the stored ratios. Each stored ratio is relative to the next node up, so the running product is that node's ratio to the root. Write it back and point the node directly at the root. The loop is iterative because a chain of 100,000 facts would exceed Python's recursion limit.
Answering a question [c, d]
- If either name was never registered, return
-1.0. This check comes first, which also coversw / wfor an unknownw. - If the roots differ, return
-1.0. - Otherwise return
ratio[c] / ratio[d]. Forc == dthis is exactly1.0.
Why it is correct
The invariant is x = ratio[x] * parent[x] for every name, as a true statement about the hidden values.
- It holds at the start, since each name is its own parent with ratio
1. - Path compression replaces a chain of links with one link whose ratio is the product of the chain's ratios. Multiplying true equalities gives a true equality.
- A union sets the new ratio algebraically from the invariant at
aandband from the fact itself, so it is also true.
Two names share a root exactly when a chain of facts connects them, since merges only happen along facts. The ratio through the root then equals the ratio along any chain, and consistency guarantees every chain agrees. Floating-point error stays far below 1e-5 because chain ratios are bounded and compression keeps products short.
Complexity
Let E = len(pairs), Q = len(asks), and V <= 2E be the number of distinct names.
- Time:
O((E + Q) log V)amortized with path compression alone. Adding union by size brings it close toO(E + Q). - Space:
O(V)for the two dictionaries, plus a temporary path list.
An alternative is to build adjacency lists, run one BFS per component from a chosen root recording each node's ratio to it, and answer questions by comparing component ids and dividing. This has the same asymptotics but is less natural if facts arrive incrementally.
Reference solution
from typing import List
def batch_ratio_lookup(pairs: List[List[str]], factors: List[float], asks: List[List[str]]) -> List[float]:
parent = {}
ratio = {} # ratio[x] = x / parent[x]
def find(x):
path = []
while parent[x] != x:
path.append(x)
x = parent[x]
root = x
acc = 1.0
# process nodes from the one nearest the root outward
for node in reversed(path):
acc *= ratio[node]
ratio[node] = acc
parent[node] = root
return root
for (a, b), v in zip(pairs, factors):
for name in (a, b):
if name not in parent:
parent[name] = name
ratio[name] = 1.0
ra = find(a)
rb = find(b)
if ra != rb:
# a = ratio[a] * ra, b = ratio[b] * rb, a / b = v
# => ra / rb = v * ratio[b] / ratio[a]
parent[ra] = rb
ratio[ra] = v * ratio[b] / ratio[a]
answers = []
for c, d in asks:
if c not in parent or d not in parent:
answers.append(-1.0)
continue
if find(c) != find(d):
answers.append(-1.0)
else:
answers.append(ratio[c] / ratio[d])
return answers