Currency Conversion Rates via Graph Traversal
Trees & GraphsModel answerLast updated
Build a weighted graph from currency pairs and answer conversion queries, then extend to directional rates and arbitrage detection.
You are given a list of currency pairs such as [('USD','CAD'), ('CAD','EUR'), ...] together with a parallel list of rates [1.1, 1.2, ...]. A rate r attached to a pair (A, B) means that 1 unit of A buys r units of B.
Part 1 (base). Assume the market is coherent: quotes are reciprocal (the rate for B → A is exactly 1/r) and consistent (every route between two currencies multiplies out to the same answer). Implement rate(src, dst) returning the conversion factor from src to dst, or -1 if no chain of exchanges connects them. State your data structures, the traversal you use, and the time/space cost of building the structure versus answering one query.
Part 2 (many queries). Queries arrive constantly and the pair list changes rarely. How does your design change?
Part 3 (follow-up). Now quotes are directional and not reciprocal: only A → B at rate r exists, and different routes give different answers. Compute the best rate from src to dst. Explain the graph model, which shortest-path algorithm is valid, how cycles correspond to arbitrage, and how floating-point error affects your comparisons.
Hints
Hint 1
Each currency is a node and each rate is the weight of a directed edge; the rate along a route is the product of its edge weights, not the sum.
Hint 2
In Part 1 every route is equally good, so any traversal that carries the running product works — but you still need a visited set, otherwise a cycle makes the search loop forever.
Hint 3
Maximizing a product is the same as minimizing a sum of negative logs; check whether those log weights are actually non-negative before you reach for Dijkstra.
Hint 4
A cycle whose product exceeds 1 is an arbitrage loop. In -log space it is a negative cycle, and it makes the answer unbounded rather than merely large.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Modeling
Currencies are nodes; each quote is a directed edge carrying a weight equal to its rate. The conversion factor along a route is the product of its edge weights, so a query is a path problem with multiplicative weights.
Storage: an adjacency list, dict[str, list[tuple[str, float]]], built once in O(E) time and O(V + E) space (Part 1 stores 2E edges because each quote also produces its reciprocal).
Part 1: coherent market
Under the consistency assumption every route between two currencies yields the same product — otherwise you could travel one way and return another, ending with more money than you started, which the assumption forbids. So any path will do and BFS is enough.
Seed a queue with (src, 1.0) and a visited set containing src. Pop (node, acc); for each neighbor, compute acc * r. If it is dst, return immediately; otherwise mark and enqueue. If the queue drains, return -1. The visited set is what makes the search terminate on cycles, and it also bounds the work: each node is expanded once, each edge examined once, so a query is O(V + E) time and O(V) space.
from collections import defaultdict, deque
class Converter:
def __init__(self, pairs, ratios):
if len(pairs) != len(ratios):
raise ValueError("pairs and ratios must align")
self.g = defaultdict(list)
for (a, b), r in zip(pairs, ratios):
if r <= 0:
raise ValueError("rate must be positive")
self.g[a].append((b, r))
self.g[b].append((a, 1.0 / r))
def rate(self, src, dst):
if src not in self.g or dst not in self.g:
return -1.0
if src == dst:
return 1.0
q = deque([(src, 1.0)])
seen = {src}
while q:
node, acc = q.popleft()
for nxt, r in self.g[node]:
if nxt in seen:
continue
val = acc * r
if nxt == dst:
return val
seen.add(nxt)
q.append((nxt, val))
return -1.0
Edge cases. A currency that appears in no pair returns -1 even when src == dst — state this convention aloud, since some interviewers prefer 1.0. A known currency queried against itself returns 1.0. Rates ≤ 0 are rejected, because 1/r and log r are undefined.
Part 2: read-heavy workload
Under consistency the answer depends only on which component a currency sits in. Run one BFS per connected component, assigning each node a value relative to the component root; then rate(a, b) = value[b] / value[a] in O(1), or -1 across components. Rebuild the labeling whenever the pair list changes. A weighted union-find gives the same result incrementally, which suits slow-changing lists with occasional insertions.
Part 3: directional, non-reciprocal quotes
Only a → b at r is added. Routes now differ, so we want the maximum product.
Transform. Maximizing ∏ rᵢ equals minimizing Σ (−log rᵢ), so set w = −log r. We then have a standard shortest-path problem.
Algorithm choice — the trap. When r > 1, −log r < 0. Real quotes above 1 are ordinary (USD→JPY is around 150), so edge weights are routinely negative, and Dijkstra is invalid: its greedy finalization assumes non-negative weights. Say this explicitly; it is the point most interviewers are probing.
- Bellman-Ford: O(V·E) time, O(V) space, handles negative weights and detects negative cycles.
- Dijkstra: valid only if every rate is ≤ 1, e.g. a fee-only model where each hop loses value.
- Floyd-Warshall: O(V³) once, all pairs at once, and arbitrage shows up as
dist[i][i] < 0— attractive when V is small (~150 real currencies) and queries are many.
Cycles and arbitrage. A negative cycle in log space is a cycle whose product exceeds 1 — a money pump. If such a cycle is reachable from src and can reach dst, the best rate is unbounded, so report infinity or an explicit flag rather than a misleading finite number. Detect it by running V−1 relaxation rounds, then one extra round; any node that still improves lies on or downstream of a negative cycle. Propagate that marking forward and test dst. A pump that cannot reach dst is irrelevant to the answer.
Floating point. Logs convert long products into sums, avoiding overflow and underflow. Compare with a tolerance, e.g. dist[u] + w < dist[v] - 1e-12; without it, rounding noise masquerades as a microscopic arbitrage and triggers spurious relaxations, especially for near-reciprocal pairs whose true product is exactly 1. Return exp(-dist[dst]). For real money movement use Decimal or fixed-point for the final amount and keep floats only inside the search.
import math
from collections import defaultdict, deque
def best_rate(pairs, ratios, src, dst, eps=1e-12):
nodes = {c for p in pairs for c in p}
if src not in nodes or dst not in nodes:
return -1.0
edges = [(a, b, -math.log(r)) for (a, b), r in zip(pairs, ratios) if r > 0]
dist = {c: math.inf for c in nodes}
dist[src] = 0.0
for _ in range(len(nodes) - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v] - eps:
dist[v] = dist[u] + w
changed = True
if not changed:
break
bad = {v for u, v, w in edges if dist[u] + w < dist[v] - eps}
if bad:
adj = defaultdict(list)
for u, v, _ in edges:
adj[u].append(v)
q, seen = deque(bad), set(bad)
while q:
x = q.popleft()
for y in adj[x]:
if y not in seen:
seen.add(y)
q.append(y)
if dst in seen:
return math.inf
return -1.0 if dist[dst] == math.inf else math.exp(-dist[dst])
src == dst yields 1.0 (distance 0) unless a pump runs through src, in which case the answer is unbounded.
Complexity summary
Index build O(E); Part 1 query O(V + E); Part 2 precompute O(V + E) per component then O(1) per query; Part 3 Bellman-Ford O(V·E) per query, or O(V³) once for all pairs.
Common mistakes
Forgetting the visited set and looping on cycles; jumping to Dijkstra in Part 3 without noticing negative log weights; treating an arbitrary cycle as arbitrage instead of a negative product-greater-than-one cycle reachable on the route; and comparing floats exactly so that a mathematically neutral round trip is flagged as a pump.