Chained Exchange Rates: Resolve Conversion Queries
Trees & GraphsAuto-graded · 16 test casesLast updated
Build a bidirectional weighted graph from exchange rates and answer conversion queries with a deterministic BFS that multiplies rates along the first-found path, or -1.0 if none exists.
An exchange desk publishes a list of direct rates. Each entry is [from_currency, to_currency, rate] and means:
1 unit of
from_currencyequalsrateunits ofto_currency.
The reverse direction is also usable: 1 unit of to_currency equals 1 / rate units of from_currency. Conversions can be chained. For example, if 1 A = 1.5 B and 1 B = 1.5 C, then 1 A = 2.25 C.
You are also given queries of the form [source, target]. Each asks how many units of target correspond to 1 unit of source. Return one float per query, in query order.
Precise procedure
The rates may be inconsistent with each other. For example, a cycle of rates may not multiply to 1, or the same pair may appear twice with different values. To make the answer unique, your function must behave exactly as the following procedure describes.
Building the graph. Process rates from first to last. For each entry [a, b, r], do these two steps in order:
- Append the edge
(b, factor = r)to the end ofa's neighbor list. - Append the edge
(a, factor = 1 / r)to the end ofb's neighbor list.
Every entry adds both edges, even if the same pair appears again. A currency exists in the graph if it appears in at least one entry, as either from_currency or to_currency.
Answering a query [source, target].
- If
source == target, the answer is1.0, even if the currency does not appear in any entry. - Otherwise, if
sourceortargetis not in the graph, the answer is-1.0. - Otherwise run a breadth-first search from
source:sourcestarts with value1.0and is marked visited.- Take currencies from the queue in first-in-first-out order. For the current currency, scan its neighbor list from front to back.
- For each neighbor that is not yet visited, mark it visited and give it the value
(current currency's value) * factor. Then add it to the back of the queue. - A currency's value is set once, when it is first discovered, and never changed.
- The answer is the value of
target. If the search ends without reachingtarget, the answer is-1.0.
When the rates are consistent, this gives the same result as multiplying along any path. When they are not, the procedure above decides the answer: the path found is the one the BFS discovers first, using the neighbor order defined above.
Answers are compared with a small floating-point tolerance. Return -1.0 (a float) for unreachable queries.
Constraints
0 <= len(rates) <= 10^40 <= len(queries) <= 10^4- Every rate is a positive number (an int or a float).
- Currency names are non-empty, case-sensitive strings.
- Rates may be listed in any order. The same pair, or a currency paired with itself, may appear more than once.
- The function must return a list of floats with exactly one entry per query.
Examples
Example 1
Input: answer_exchange_queries([['A', 'B', 1.5], ['B', 'C', 1.5]], [['A', 'C'], ['C', 'A'], ['A', 'A'], ['A', 'D']])
Output: [2.25, 0.4444444444444444, 1, -1]
Example 2
Input: answer_exchange_queries([['USD', 'EUR', 0.9], ['EUR', 'JPY', 160]], [['USD', 'JPY'], ['JPY', 'USD']])
Output: [144, 0.006944444444444445]
Hints
Hint 1
Treat each currency as a node. Every rate gives you two directed edges, one with weight `rate` and one with weight `1 / rate`, appended in the order described.
Hint 2
Run a BFS from the source, carrying the running product of factors. A neighbor gets its value only the first time it is discovered. Stop when you reach the target.
Hint 3
Handle `source == target` first (always 1.0), then return -1.0 if either currency is missing from the graph. A weighted union-find is faster for many queries, but it only agrees with the BFS rule when the data is consistent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model currencies as nodes of a weighted graph. For each rate [a, b, r], meaning 1 a = r b, append an edge a -> b with factor r to a's list, then an edge b -> a with factor 1 / r to b's list. Adjacency lists therefore keep input order.
To answer a query, handle the special cases first:
- If
source == target, return1.0. - If either currency is not in the graph, return
-1.0. - Otherwise run a BFS from
sourcewith value1.0. Each newly discovered neighbor getscurrent value * factor. Whentargetis reached, its stored value is the answer. If the queue empties first, return-1.0.
Why it is correct
Chaining conversions means multiplying rates, and the reciprocal edge makes each rate usable in both directions. The visited set means every currency is assigned a value exactly once, the first time BFS reaches it. That fixes the answer deterministically even if the rates contradict each other, because the path is determined by BFS order and the neighbor order. If the rates are consistent, any path gives the same value. If target is unreachable, it lies in a different connected component, so -1.0 is right. The special cases follow the stated rules.
Complexity
- Building the graph takes O(E) time and space for E rates.
- Each query's BFS takes O(V + E) time and O(V) space, so the total is O(E + Q * (V + E)) for Q queries.
Note on scaling
A weighted union-find or a per-component precomputation can answer queries in near O(1). However, they bake in a single value per currency per component. They match the BFS rule only when the rates are consistent. The BFS version follows the stated procedure exactly and fits within the constraints.
Reference solution
from collections import deque
from typing import List
def answer_exchange_queries(rates: List[List], queries: List[List[str]]) -> List[float]:
graph = {}
for source, target, rate in rates:
graph.setdefault(source, []).append((target, float(rate)))
graph.setdefault(target, []).append((source, 1.0 / float(rate)))
answers = []
for source, target in queries:
if source == target:
answers.append(1.0)
continue
if source not in graph or target not in graph:
answers.append(-1.0)
continue
queue = deque([(source, 1.0)])
visited = {source}
result = -1.0
while queue:
currency, amount = queue.popleft()
if currency == target:
result = amount
break
for neighbor, factor in graph[currency]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, amount * factor))
answers.append(result)
return answers