Detect a currency arbitrage cycle in directed exchange rates
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given directed currency exchange rates, decide whether some sequence of exchanges that starts and ends in the same currency leaves you with more than you started with. It tests modeling rates as a weighted directed graph, finding a profitable cycle anywhere in it, and handling floating-point precision.
Constraints
- 2 <= n <= 500
- 1 <= len(rates) <= n * (n - 1)
- 0 <= rates[i][0], rates[i][1] < n
- rates[i][0] != rates[i][1]
- 0.001 <= rates[i][2] <= 1000.0
- All (from, to) pairs are unique.
- For every cycle, the product of its rates is either at most 1 or at least 1.000001.
Examples
Input: (3, [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]])
Expected Output: True
Explanation: Source example 1: the cycle 0 -> 1 -> 2 -> 0 multiplies to 1.2 × 1.3 × 0.9 = 1.404.
Input: (3, [[0, 1, 0.5], [1, 2, 0.5], [2, 0, 0.5]])
Expected Output: False
Explanation: Source example 2: the only cycle multiplies to 0.125.
Hints
- An opportunity may start at any currency, so a profitable cycle can sit in a part of the graph that currency 0 cannot reach.
- Products along long cycles can grow past the largest double, so think about how to compare a cycle's product with 1 without forming that product directly.
- A cycle whose product is exactly 1, such as 2.0 followed by 0.5, must not count, and the tests promise every profitable cycle reaches at least 1.000001, so a comparison tolerance far below that gap is safe.