Multi-Hop Currency Conversion Over a Rate Table
Trees & GraphsAuto-graded · 25 test casesLast updated
Compute a conversion factor between two currencies by chaining and inverting listed rates, returning -1.0 when no chain exists; tests graph traversal with multiplicative weights.
Multi-Hop Currency Conversion
A exchange desk keeps a list of quotes. Each quote is a triple (base, quote, rate) stating that one unit of base can be exchanged for rate units of quote. For instance, ("USD", "GBP", 0.77) says 1 USD is worth 0.77 GBP.
You are given the list of quotes, a source currency and a target currency. Return the number of units of target that one unit of source is worth. The pair you need may not be quoted directly, so the conversion may have to pass through one or more intermediate currencies.
Rules
- Every quote works in both directions. If
(A, B, r)is listed, then 1Bis also worth1 / runits ofA. - Rates multiply along a chain. If 1
Ais worthxunits ofBand 1Bis worthyunits ofC, then 1Ais worthx * yunits ofC. - The quotes are mutually consistent: any two chains linking the same pair of currencies give the same rate (up to floating-point rounding). The correct answer is therefore unique.
- If
source == target, return1.0, even when that currency appears in no quote. - Otherwise, if no chain of quotes links
sourcetotarget(including when either one is absent from the quotes), return-1.0. - A positive answer is accepted if its relative error from the exact value is at most
1e-6. The value-1.0must be returned exactly when no conversion is possible.
Input
rates: a list of triples(base, quote, rate)with string currency codes and a float rate. Entries may be given as lists.source: the starting currency code.target: the destination currency code.
Output
A float: the conversion factor from source to target, or -1.0 if unreachable.
Constraints
0 <= len(rates) <= 10000- Every currency code (including
sourceandtarget) is a string of 3 uppercase English letters. - In each quote
base != quote, and every unordered pair of currencies appears in at most one quote. 1e-3 <= rate <= 1e3for every quote.- The exact rate between any two connected currencies is between
1e-9and1e9, so intermediate products never overflow or underflow a 64-bit float.
Examples
Example 1
Input: convert_rate([['USD', 'GBP', 0.77], ['GBP', 'EUR', 1.2]], 'USD', 'EUR')
Output: 0.9239999999999999
Example 2
Input: convert_rate([['USD', 'GBP', 0.77], ['GBP', 'EUR', 1.2]], 'EUR', 'USD')
Output: 1.0822510822510822
Example 3
Input: convert_rate([['USD', 'GBP', 0.77], ['JPY', 'KRW', 9.5]], 'USD', 'KRW')
Output: -1
Hints
Hint 1
Think of each currency as a node and each quote as a connection that can be walked in either direction.
Hint 2
Because the quotes are consistent, you do not need the best or shortest chain: any chain gives the right answer, so a simple traversal is enough.
Hint 3
While traversing, remember for every reached currency how many units of it one unit of the source is worth. Check source == target before you check whether the currencies appear in the table.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the quotes as a graph. Each currency is a node. A quote (A, B, r) creates two weighted edges: A -> B with weight r and B -> A with weight 1 / r. A conversion chain is a path, and its overall rate is the product of the edge weights along it.
Since the table is consistent, every path between two currencies yields the same product. That means no shortest-path or best-path algorithm is needed. Any path is fine, so a plain breadth-first search works (and avoids recursion-depth problems on long chains).
Steps:
- If
source == target, return1.0immediately. This must come first, because the currency may not appear in the table at all. - Build the adjacency lists with both the forward and the reciprocal edge.
- If either currency is missing from the graph, return
-1.0. - Run BFS from
source, keepingworth[c], the number of units ofcthat one unit ofsourceis worth. Start withworth[source] = 1.0. When moving fromxto an unvisited neighboryover an edge of weightr, setworth[y] = worth[x] * r. - When
targetis dequeued, return its value. If the queue empties first, return-1.0.
Why it is correct
Invariant: for every currency c in worth, worth[c] is the product of weights along some path from source to c, which is the exchange rate from source to c. It holds for source (empty path, product 1), and extending a path by an edge multiplies by that edge's weight, which is exactly the chaining rule. By consistency, the path BFS finds gives the unique exact rate. BFS visits every node in the source's connected component, so if target is reachable it is found; otherwise no chain exists and -1.0 is right. The worth dictionary also serves as the visited set, so cycles cannot cause infinite loops.
Floating-point error grows only with the number of multiplications, roughly 1e-16 each, which stays far below the 1e-6 tolerance even for very long chains.
Complexity
With E quotes and V <= 2E distinct currencies:
- Time: O(V + E) for building the graph and the BFS.
- Space: O(V + E) for the adjacency lists, the
worthmap and the queue.
Reference solution
from collections import deque
from typing import List, Tuple
def convert_rate(quotes: List[Tuple[str, str, float]], source: str, target: str) -> float:
if source == target:
return 1.0
graph = {}
for a, b, r in quotes:
graph.setdefault(a, []).append((b, r))
graph.setdefault(b, []).append((a, 1.0 / r))
if source not in graph or target not in graph:
return -1.0
worth = {source: 1.0}
queue = deque([source])
while queue:
cur = queue.popleft()
if cur == target:
return worth[cur]
for nxt, r in graph[cur]:
if nxt not in worth:
worth[nxt] = worth[cur] * r
queue.append(nxt)
return -1.0