Finding Profitable Exchange Cycles with Transaction Fees
Trees & GraphsModel answerLast updated
Given exchange rates between currencies and a per-cycle transaction cost, determine if any sequence of trades can yield a profit.
You're analyzing currency markets to find trading opportunities. You have access to a K×K matrix of exchange rates where entry rates[i][j] represents how much of currency j you receive for one unit of currency i. The diagonal entries satisfy rates[i][i] = 1.
When you complete a full cycle of trades (starting and ending with the same currency), you pay a transaction fee equal to 0.01% of your initial amount.
Write a function that determines whether any sequence of currency exchanges exists that would leave you with strictly more money than you started with, after accounting for the transaction fee.
Input:
rates: a K×K matrix of positive floats representing exchange rates
Output:
Trueif a profitable trading cycle exists,Falseotherwise
Example:
rates = [
[1.0, 0.9, 1.5],
[1.1, 1.0, 0.8],
[0.7, 1.2, 1.0]
]
# Currency 0 → 1 → 2 → 0 gives: 0.9 × 1.2 × 0.7 = 0.756 (loss)
# Currency 0 → 2 → 1 → 0 gives: 1.5 × 1.2 × 1.1 = 1.98 (profit even after 0.01% fee)
# Returns True
Constraints:
- 1 ≤ K ≤ 200
- All rates are positive floats
- The fee applies once per completed cycle, not per individual trade
Hints
Hint 1
Consider what happens if you find a cycle with any profit at all—could you exploit it multiple times within a single 'round trip'?
Hint 2
Converting exchange rates to logarithms transforms products into sums, making this a classic graph problem.
Hint 3
This problem reduces to finding a specific type of cycle in a weighted directed graph.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Negative Cycle Detection via Bellman-Ford
Understanding the Problem
The critical insight is recognizing what the fixed per-cycle fee actually means. Starting with amount A and executing trades along a cycle with cumulative exchange rate product P, you end with P·A. After the 0.01% fee (0.0001·A), your profit condition is:
P·A - 0.0001·A > A
P > 1.0001
However, if any cycle has P > 1, you can repeat it multiple times within what counts as a single "cycle" for fee purposes. If P > 1, then P^k grows without bound as k increases. Eventually P^k > 1.0001 for large enough k.
Conversely, if all cycles have P ≤ 1, no combination of trades can exceed the starting amount.
Key insight: The fixed transaction cost becomes irrelevant when repetition is allowed. We simply need to detect whether any cycle exists with product strictly greater than 1.
Graph Transformation
Working directly with products is cumbersome for graph algorithms. Apply logarithms:
Product > 1 ⟺ log(Product) > 0 ⟺ Σ log(rate) > 0
Define edge weights as the negative log of exchange rates:
weight(i → j) = -log(rates[i][j])
Now a profitable cycle (product > 1) corresponds to a negative-weight cycle (sum of weights < 0).
Algorithm: Bellman-Ford
Bellman-Ford detects negative cycles in directed graphs:
- Build a weighted directed graph where each currency is a node and each non-zero exchange rate creates an edge
- Initialize distances: set
dist[v] = 0for all vertices (simulates a virtual source connected to all nodes) - Relax all edges K-1 times
- Check if any edge can still be relaxed—if yes, a negative cycle exists
Why K-1 iterations suffice: Without negative cycles, the shortest path from any source uses at most K-1 edges. If distances still change after K-1 rounds, a negative cycle must exist.
Handling Floating-Point Precision
Exchange rates like 1.1 and 0.909... might theoretically form a neutral cycle (product = 1.0) but appear slightly profitable due to rounding errors. Use a small epsilon (e.g., 1e-12) when comparing distances to avoid false positives.
Complexity Analysis
- Time: O(K³) — K rounds of relaxation, each examining K² edges in the dense graph
- Space: O(K²) for storing edge weights, O(K) for distance array
Implementation
import math
from typing import List
def has_arbitrage(rates: List[List[float]]) -> bool:
"""
Detect if any cycle of currency exchanges yields profit after
accounting for a 0.01% transaction fee per completed cycle.
Since profitable cycles can be repeated, this reduces to finding
any cycle with exchange rate product > 1, equivalent to finding
a negative cycle in the log-transformed weight graph.
"""
K = len(rates)
if K < 2:
return False
# Build edge list with weights = -log(rate)
# Skip self-loops and zero/missing rates
edges = []
for i in range(K):
for j in range(K):
if i != j and rates[i][j] > 0:
weight = -math.log(rates[i][j])
edges.append((i, j, weight))
# Initialize distances (virtual source at distance 0 to all nodes)
dist = [0.0] * K
eps = 1e-12
# Relax edges K-1 times
for _ in range(K - 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:
# Converged early, no negative cycle
return False
# Check for further relaxation (indicates negative cycle)
for u, v, w in edges:
if dist[u] + w < dist[v] - eps:
return True
return False
Edge Cases
- K ≤ 1: No multi-currency cycle possible, return
False - Consistent rates: All cycles have product exactly 1 (no arbitrage)
- Two-currency arbitrage:
rates[0][1] × rates[1][0] > 1should be detected - Disconnected components: Virtual source initialization handles all components
- Zero entries: Represent missing markets; skip these edges
Common Mistakes
- Applying the fee per trade instead of per cycle: This fundamentally changes the problem
- Trying to incorporate 1.0001 into edge weights: The threshold is per-cycle, not per-edge
- Ignoring floating-point precision: Can lead to false positives on neutral cycles
- Using DFS for cycle detection: Doesn't account for the fact that we need the best cycle product
Follow-up Extensions
- Return the actual cycle: Maintain a predecessor array and trace back when a negative cycle is detected
- No currency repetition allowed: Becomes NP-hard; requires dynamic programming with bitmask for small K
- Per-trade fees instead: Multiply each rate by (1 - fee_rate) before transforming, so fees fold into edge weights naturally