Quick 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.

Detect a currency arbitrage cycle in directed exchange rates

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given `n` currencies labeled from `0` to `n - 1` and a list of directed exchange `rates`. Determine whether there exists an **arbitrage opportunity**. An arbitrage opportunity exists when you can start with some amount of a currency, perform a series of exchanges through other currencies, and end up with **more** of the original currency than you started with. Each exchange rate is represented as `[from, to, rate]`, meaning you can exchange `1` unit of currency `from` for `rate` units of currency `to`. Return `True` if an arbitrage opportunity exists, otherwise return `False`. ### Function Signature ```python def has_arbitrage(n: int, rates: list[list[float]]) -> bool: ``` ### Rules - In each entry of `rates`, `from` and `to` are integer currency indices and `rate` is a positive number. - Rates are directed. Exchanging `b` back into `a` is possible only if `rates` also has an entry from `b` to `a`. - An opportunity must end in the currency it started from, and the product of the rates along the way must be strictly greater than 1. A cycle whose product is exactly 1 does not count. - A cycle may start at any currency and pass through any number of other currencies. - The tests avoid floating-point borderline cases: for every cycle, the product of its rates is either at most 1 or at least 1.000001. ### 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. ### Examples ```text Input: n = 3, rates = [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]] Output: True ``` Starting with 1 unit of currency 0 and exchanging along `0 -> 1 -> 2 -> 0` gives 1 × 1.2 × 1.3 × 0.9 = 1.404 units of currency 0, which is more than the starting amount. ```text Input: n = 3, rates = [[0, 1, 0.5], [1, 2, 0.5], [2, 0, 0.5]] Output: False ``` The only cycle is `0 -> 1 -> 2 -> 0`, and its product is 0.5 × 0.5 × 0.5 = 0.125, so every trip around it loses money. ```text Input: n = 3, rates = [[0, 1, 2.0], [1, 0, 0.5], [1, 2, 3.0]] Output: False ``` The round trip `0 -> 1 -> 0` returns exactly 2.0 × 0.5 = 1 unit, which is not more than the starting amount. The exchange from 1 to 2 triples the amount, but no rate leads out of currency 2, so that money never returns to the currency it started in.

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.

You are given `n` currencies labeled from `0` to `n - 1` and a list of directed exchange `rates`. Each entry of `rates` is `[from, to, rate]`, meaning you can exchange 1 unit of currency `from` for `rate` units of currency `to`. Determine whether an arbitrage opportunity exists. An arbitrage opportunity exists when you can start with some amount of a currency, perform a series of exchanges through other currencies, and end up with more of the original currency than you started with. Rules: - In each entry of `rates`, `from` and `to` are integer currency indices and `rate` is a positive number. - Rates are directed. Exchanging `b` back into `a` is possible only if `rates` also has an entry from `b` to `a`. - An opportunity must end in the currency it started from, and the product of the rates along the way must be strictly greater than 1. A cycle whose product is exactly 1 does not count. - A cycle may start at any currency and pass through any number of other currencies. - The tests avoid floating-point borderline cases: for every cycle, the product of its rates is either at most 1 or at least 1.000001. Return `True` if an arbitrage opportunity exists, otherwise return `False`. Input types: `n` is an integer and `rates` is a list of numeric rows. Java receives `rates` as `double[][]` and C++ as `std::vector<std::vector<double>>`, so the two currency indices in each row arrive as whole-number doubles. No input value exceeds 2^31 - 1, but the product of the rates along a long cycle can exceed the largest double (1000.0 multiplied 500 times is 10^1500). Example 1: ```text Input: n = 3, rates = [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]] Output: True ``` Starting with 1 unit of currency 0 and exchanging along `0 -> 1 -> 2 -> 0` gives 1 × 1.2 × 1.3 × 0.9 = 1.404 units of currency 0, which is more than the starting amount. Example 2: ```text Input: n = 3, rates = [[0, 1, 2.0], [1, 0, 0.5], [1, 2, 3.0]] Output: False ``` The round trip `0 -> 1 -> 0` returns exactly 2.0 × 0.5 = 1 unit, which is not more than the starting amount. The exchange from 1 to 2 triples the amount, but no rate leads out of currency 2, so that money never returns to the currency it started in.

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

  1. An opportunity may start at any currency, so a profitable cycle can sit in a part of the graph that currency 0 cannot reach.
  2. 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.
  3. 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.

Detect a Profitable Currency Exchange Cycle

mediumGeneralSoftware Engineer

You are given n currencies labeled from 0 to n - 1 and a list of directed exchange rates. Each entry of rates is [from, to, rate], meaning you can exchange 1 unit of currency from for rate units of currency to. Determine whether an arbitrage opportunity exists.

An arbitrage opportunity exists when you can start with some amount of a currency, perform a series of exchanges through other currencies, and end up with more of the original currency than you started with.

Rules:

  • In each entry of rates, from and to are integer currency indices and rate is a positive number.
  • Rates are directed. Exchanging b back into a is possible only if rates also has an entry from b to a.
  • An opportunity must end in the currency it started from, and the product of the rates along the way must be strictly greater than 1. A cycle whose product is exactly 1 does not count.
  • A cycle may start at any currency and pass through any number of other currencies.
  • The tests avoid floating-point borderline cases: for every cycle, the product of its rates is either at most 1 or at least 1.000001.

Return True if an arbitrage opportunity exists, otherwise return False.

Input types: n is an integer and rates is a list of numeric rows. Java receives rates as double[][] and C++ as std::vector<std::vector<double>>, so the two currency indices in each row arrive as whole-number doubles. No input value exceeds 2^31 - 1, but the product of the rates along a long cycle can exceed the largest double (1000.0 multiplied 500 times is 10^1500).

Example 1:

Input: n = 3, rates = [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]]
Output: True

Starting with 1 unit of currency 0 and exchanging along 0 -> 1 -> 2 -> 0 gives 1 × 1.2 × 1.3 × 0.9 = 1.404 units of currency 0, which is more than the starting amount.

Example 2:

Input: n = 3, rates = [[0, 1, 2.0], [1, 0, 0.5], [1, 2, 3.0]]
Output: False

The round trip 0 -> 1 -> 0 returns exactly 2.0 × 0.5 = 1 unit, which is not more than the starting amount. The exchange from 1 to 2 triples the amount, but no rate leads out of currency 2, so that money never returns to the currency it started in.

Examples

Example 1
Input
(3, [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]])
Output
True
Notes
Source example 1: the cycle 0 -> 1 -> 2 -> 0 multiplies to 1.2 × 1.3 × 0.9 = 1.404.
Example 2
Input
(3, [[0, 1, 0.5], [1, 2, 0.5], [2, 0, 0.5]])
Output
False
Notes
Source example 2: the only cycle multiplies to 0.125.

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.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def has_arbitrage(n: int, rates: list[list[float]]) -> bool:
Sample call
has_arbitrage(3, [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]])
Language
Case 1
Input
(3, [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]])
Expected
True
Case 2
Input
(3, [[0, 1, 0.5], [1, 2, 0.5], [2, 0, 0.5]])
Expected
False

Browse More Questions

Show the approach

Approach

Replace each rate with the weight w = -ln(rate). The product of the rates on a cycle is greater than 1 exactly when the sum of their weights is negative, so the question becomes whether the weighted directed graph has a negative cycle. Sums of logarithms also stay small: a running product of 1000.0 rates passes the largest double (about 1.8 × 10^308) after 103 exchanges, while the matching weight sum is only about -711.5.

Algorithm: Bellman-Ford from a virtual source that reaches every currency through a weight-0 edge, which is the same as starting every distance at 0. Starting everywhere lets the search find a cycle in any part of the graph, including parts that currency 0 cannot reach. Each round scans every rate once and sets dist[to] = dist[from] + w only when that lowers dist[to] by more than a tolerance of 1e-9. If a whole round changes nothing, return False. If all n rounds change something, return True.

Correctness: Suppose some cycle of length L has product at least 1.000001. Its weights sum to at most -ln(1.000001), about -9.99999 × 10^-7. The slacks dist[v] - dist[u] - w on the edges of that cycle always add up to the negated weight sum, which is more than 500 × 10^-9 >= L × 10^-9, so some edge on the cycle can always be lowered by more than the tolerance and no round is ever quiet. Suppose instead that every cycle has product at most 1. A change in round r at currency v comes from a change at the edge's source made after that edge was last scanned, so in round r or r - 1. A change in round n therefore needs a chain of at least n changes along a walk of n edges, which repeats a currency. Every change on that chain lowered a distance by more than the tolerance, so the repeated stretch would be a cycle with a negative weight sum, which does not exist. Round n is therefore quiet and the answer is False.

Floating point: a cycle whose product is exactly 1 in decimal, such as 10.0 and 0.1, can give a weight sum of about 10^-16 below zero after rounding. The tolerance stops that rounding from counting as profit, and the guaranteed gap up to 1.000001 keeps every real profit far above the tolerance even on a 500-edge cycle.

Edge cases: a single rate or any graph without a cycle stops at its first quiet round, which comes no later than round n; currencies that appear in no rate keep distance 0 and never change the answer.

Time complexity:
O(n * m), where m = len(rates)
Space complexity:
O(n + m)