Detect a Profitable Currency Trade Loop
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests whether you can model exchange rates as a weighted directed graph and apply Bellman-Ford to detect a cycle whose rate product exceeds 1.
Detect a Profitable Currency Trade Loop
You are given a list of currency exchange rates. Each entry is a triple [source, target, rate] meaning: starting with 1 unit of source, you receive rate units of target.
If you chain a sequence of trades, your final holdings equal the product of the rates along that sequence. A profitable loop exists when you can start and end on the same currency and end up with strictly more than 1 unit — that is, the product of rates around the cycle is greater than 1.
Write a function that returns True if such a loop exists anywhere in the exchange network, and False otherwise.
Constraints
0 ≤ len(rates) ≤ 10 000- Each
sourceandtargetis a non-empty string representing a currency code. - The number of distinct currencies is at most 100.
- Every
rateis a positive floating-point number. - A valid loop requires at least one trade (a self-loop
['USD', 'USD', 1.05]qualifies). - The exchange network may consist of multiple disconnected components; a profitable loop in any component counts.
- Treat any apparent profit smaller than 1 part in 10⁹ as floating-point noise, not a real gain.
- Multiple entries for the same currency pair are allowed; each is a separate potential trade.
Examples
Example 1
Input: can_make_profit([['USD', 'EUR', 0.9], ['EUR', 'GBP', 0.8], ['GBP', 'USD', 1.5]])
Output: True
Example 2
Input: can_make_profit([['USD', 'EUR', 0.5], ['EUR', 'USD', 1.5]])
Output: False
Hints
Hint 1
A product of rates being greater than 1 is equivalent to the sum of their logarithms being positive — try reformulating the problem as a sum over a cycle instead of a product.
Hint 2
Once you have a sum formulation, negating the log-weights turns 'cycle product > 1' into 'negative-weight cycle'. A classic shortest-path algorithm can detect exactly that.
Hint 3
The exchange network may be disconnected. Think about how to make sure every currency is reachable from your starting point without actually adding a new node — initializing all distances to the same value achieves the same effect as a virtual source.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reformulating the problem
Checking whether a product of numbers exceeds 1 is awkward to handle with graph algorithms, which deal in sums. Taking the natural logarithm converts the product condition into a sum condition:
r1 × r2 × … × rk > 1
⟺ log(r1) + log(r2) + … + log(rk) > 0
⟺ −log(r1) + −log(r2) + … + −log(rk) < 0
So we assign each directed edge source → target the weight −log(rate). A profitable trade loop is then exactly a negative-weight cycle in this transformed graph.
Why Bellman-Ford works here
Bellman-Ford finds shortest paths by repeatedly relaxing every edge. After at most n − 1 rounds (where n is the number of vertices), all shortest paths in a cycle-free graph have stabilized. If any edge can still be relaxed on the n-th round, there must be a negative-weight cycle reachable from the start — otherwise shortest paths would already be optimal.
Handling disconnected components
Instead of picking a single start currency (which might miss currencies in other components), we initialize every vertex's distance to 0. This is mathematically equivalent to adding a virtual source with a zero-weight edge to every vertex. The correctness of Bellman-Ford is unchanged; we simply cover all components at once.
Floating-point epsilon
Because log and floating-point arithmetic introduce tiny rounding errors, a cycle whose true product is exactly 1 might produce a sum of −1e-16 rather than exactly 0. We only count a relaxation as real if it improves the distance by more than 1e-9, which ignores any apparent gain smaller than one part in a billion.
Why the algorithm is correct
- After
n − 1rounds without finding a negative cycle, all shortest paths are finalized (standard Bellman-Ford correctness). - If a negative-weight cycle exists, at least one of its edges will always be relaxable — distances on that cycle never stabilize — so the
n-th round is guaranteed to find one. - Every valid trade loop has at least one edge, satisfying the "at least one exchange" requirement. Even a self-loop (
source == target,rate > 1) is handled correctly since it relaxes immediately.
Complexity
- Time:
O(V × E). With at most 100 currencies and up to 10,000 rate entries, this is at most 10⁶ relaxations. Early exit (when a round makes no updates) often terminates well before that. - Space:
O(V + E)for the index map, edge list, and distance array.
An alternative is Floyd-Warshall on the max-product rates, checking whether any best[i][i] > 1 after propagation. It runs in O(V³) ≈ 10⁶ here and is simpler to code, but scales worse than Bellman-Ford on sparse graphs.
Full solution
import math
from typing import List
def can_make_profit(rates: List[List]) -> bool:
if not rates:
return False
# Assign a numeric index to every distinct currency.
currency_index = {}
for source, target, rate in rates:
for currency in (source, target):
if currency not in currency_index:
currency_index[currency] = len(currency_index)
n = len(currency_index)
# Transform each rate r to a weight -log(r).
# A cycle whose rates multiply to > 1 has log-sum > 0,
# which means the transformed weight sum is negative —
# exactly a negative-weight cycle.
edges = [
(currency_index[src], currency_index[dst], -math.log(rate))
for src, dst, rate in rates
]
# Initialize every distance to 0. This is equivalent to adding a
# virtual source with a zero-weight edge to every vertex, so all
# components of a disconnected graph are covered simultaneously.
dist = [0.0] * n
# Bellman-Ford: relax all edges n times.
# If a relaxation succeeds on the n-th round, a negative cycle exists.
EPS = 1e-9
for iteration in range(n):
updated = False
for u, v, w in edges:
if dist[u] + w < dist[v] - EPS:
dist[v] = dist[u] + w
updated = True
if iteration == n - 1:
# Still relaxing on the final round → negative cycle found.
return True
if not updated:
# Converged early; no negative cycle possible.
return False
return False