KatInterview

Detect a Profitable Currency Trade Loop

Trees & GraphsAuto-graded · 20 test cases
HardAuto-gradedTrees & Graphsgraphsbellman-fordlogarithms

Last 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 source and target is a non-empty string representing a currency code.
  • The number of distinct currencies is at most 100.
  • Every rate is 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.