Find a Money-Making Loop in a Table of Exchange Rates
Trees & GraphsModel answerLast updated
Given directed currency exchange quotes, decide whether some round trip returns more than it started with, and output one such round trip as an ordered list of currencies.
A trading desk receives a feed of exchange quotes. Each quote is a tuple (src, dst, rate): one unit of src can be exchanged for rate units of dst. Example: ("USD", "EUR", 0.9).
A round-trip gain is a chain of exchanges that begins and ends in the same currency and leaves you with strictly more than you started with, once every rate along the chain has been applied in order.
Write a function that:
- Detects whether any round-trip gain exists in the quotes.
- Returns one such chain as the list of currencies visited in order, with the first and last entries equal, for example
["USD", "EUR", "GBP", "USD"]. If none exists, return an empty result.
State your assumptions about the following before you code, or discuss them with the interviewer:
- Are quotes usable only in the listed direction, or can they be inverted?
- Are there fees or spreads, and can any amount be exchanged?
- How do you treat floating-point error: is any product above 1 a gain, or only one above a tolerance?
- If several gainful chains exist, is any one acceptable?
- Can a pair be quoted several times with different rates?
- How large can the number of currencies and quotes be?
Part 1. Decide whether a gainful chain exists anywhere in the quote graph, not just among currencies reachable from one chosen start. Give the time complexity and explain how you handle floating-point rounding.
Part 2. When one exists, return a concrete gainful chain in forward conversion order, containing only the loop itself (no lead-in path), and verify that its rate product is greater than 1.
Hints
Hint 1
A chain's total gain is the product of its rates. Which standard transformation turns a product into a sum, and what does 'product greater than 1' become after it?
Hint 2
After taking -log of each rate, you are looking for a negative-weight cycle. Think about which shortest-path algorithm detects that, and how to make it work when the graph is not connected (for example, start every distance at 0).
Hint 3
To recover the loop, store a predecessor for each node when it is relaxed. If a relaxation still succeeds on the V-th pass, walk back V times along predecessors to guarantee you are inside the cycle, then follow predecessors until you return to that node and reverse the result.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model
Treat each currency as a node and each quote (src, dst, rate) as a directed edge src -> dst. Following a chain multiplies the rates. A chain is profitable if the product of its rates exceeds 1.
Products are awkward, so take logarithms. Give each edge the weight w = -ln(rate). Then:
rate1 * rate2 * ... * ratek > 1
<=> sum(ln rate_i) > 0
<=> sum(-ln rate_i) < 0
So a profitable round trip is exactly a negative-weight cycle in the transformed graph. Detecting arbitrage becomes detecting a negative cycle.
Algorithm (Bellman-Ford)
- Index the currencies, giving V nodes and E edges.
- Set
dist[v] = 0for all nodes. This acts like a virtual source connected to everything with weight 0, so cycles in any disconnected component are found. Setpred[v] = -1. - Repeat V times: for each edge
(u, v, w), ifdist[u] + w < dist[v] - eps, setdist[v] = dist[u] + w,pred[v] = u, and remembervas the last relaxed node. - If a full pass makes no update, there is no negative cycle, so return nothing. If the V-th pass still relaxes an edge, a negative cycle exists.
Complexity: O(V·E) time, O(V) extra space. With dense quotes (E close to V²), Floyd-Warshall on the log matrix is O(V³) and is a reasonable alternative. A negative diagonal entry signals a cycle. It needs O(V²) memory, though, and path reconstruction needs a "next" matrix.
Reconstructing the cycle
The node whose relaxation succeeded on the V-th pass is either on a negative cycle or reachable from one through predecessor links. So:
- Let
xbe that node. Stepx = pred[x]V times. After V steps,xis guaranteed to lie on the cycle. - Starting at
x, followpreduntil you return tox, collecting nodes. - Reverse the collected list, since
predpoints backward, and append the start node so the first and last entries are equal.
This yields only the loop with no lead-in path.
Floating-point tolerance
Rounding can create fake gains: a pair of reciprocal quotes such as 0.9 and 1/0.9 might multiply to 1.0000000000000002. It can also hide tiny real ones.
- Use a relaxation threshold
eps(for example1e-12, or a value tied to the rate precision in the feed, such as1e-9if rates have 6 to 8 significant digits). Only relax when the improvement exceedseps. - The logarithm helps because errors add instead of compounding multiplicatively, so a tolerance on the sum is easy to reason about.
- Finally, verify the returned chain by multiplying the original rates and requiring a product above
1 + tol. If it fails, treat it as noise. If you want to be rigorous, useDecimalorFractionfor the final check.
Code (Python)
import math
def find_arbitrage(quotes, eps=1e-12):
idx, names = {}, []
for a, b, _ in quotes:
for c in (a, b):
if c not in idx:
idx[c] = len(names)
names.append(c)
n = len(names)
edges = [(idx[a], idx[b], -math.log(r)) for a, b, r in quotes if r > 0]
best_rate = {}
for a, b, r in quotes:
if r > 0:
best_rate[(idx[a], idx[b])] = max(best_rate.get((idx[a], idx[b]), 0), r)
dist = [0.0] * n
pred = [-1] * n
x = -1
for _ in range(n):
x = -1
for u, v, w in edges:
if dist[u] + w < dist[v] - eps:
dist[v] = dist[u] + w
pred[v] = u
x = v
if x == -1:
return []
for _ in range(n):
x = pred[x]
cycle, cur = [x], pred[x]
while cur != x:
cycle.append(cur)
cur = pred[cur]
cycle.append(x)
cycle.reverse()
prod = 1.0
for a, b in zip(cycle, cycle[1:]):
prod *= best_rate[(a, b)]
return [names[i] for i in cycle] if prod > 1 + 1e-9 else []
Duplicate quotes for the same pair are handled naturally: Bellman-Ford keeps the best edge, and best_rate keeps the verification consistent with that choice.
Common mistakes
- Running Bellman-Ford from a single source, which misses cycles in unreachable components.
- Using
+lnand looking for a positive cycle with a shortest-path routine. - Returning the node found at the V-th pass without walking back V steps, which may output a lead-in path that is not a cycle.
- Forgetting to reverse the predecessor walk, so the chain runs backwards.
- Comparing a product to exactly 1 with no tolerance.
- Assuming reciprocals are available when the feed lists only one direction.
Tests
- No opportunity: consistent rates such as USD->EUR 0.5, EUR->USD 2.0 give an empty result.
- Two-currency loop: USD->EUR 0.9 and EUR->USD 1.2 give a gain of 1.08.
- A currency quoted against itself with a rate above 1 is a one-edge cycle. With rate exactly 1 it is not a gain.
- Disconnected components where only the second contains a gain.
- Reciprocal quotes whose product is exactly 1 must not be flagged because of rounding.
- Duplicate quotes for a pair with different rates.