KatInterview

Find a Money-Making Loop in a Table of Exchange Rates

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraphbellman-fordnegative-cycle

Last updated

Given directed currency exchange quotes, decide whether some round trip returns more than it started with, and output one such round trip as an ordered list of currencies.

A trading desk receives a feed of exchange quotes. Each quote is a tuple (src, dst, rate): one unit of src can be exchanged for rate units of dst. Example: ("USD", "EUR", 0.9).

A round-trip gain is a chain of exchanges that begins and ends in the same currency and leaves you with strictly more than you started with, once every rate along the chain has been applied in order.

Write a function that:

  1. Detects whether any round-trip gain exists in the quotes.
  2. Returns one such chain as the list of currencies visited in order, with the first and last entries equal, for example ["USD", "EUR", "GBP", "USD"]. If none exists, return an empty result.

State your assumptions about the following before you code, or discuss them with the interviewer:

  • Are quotes usable only in the listed direction, or can they be inverted?
  • Are there fees or spreads, and can any amount be exchanged?
  • How do you treat floating-point error: is any product above 1 a gain, or only one above a tolerance?
  • If several gainful chains exist, is any one acceptable?
  • Can a pair be quoted several times with different rates?
  • How large can the number of currencies and quotes be?

Part 1. Decide whether a gainful chain exists anywhere in the quote graph, not just among currencies reachable from one chosen start. Give the time complexity and explain how you handle floating-point rounding.

Part 2. When one exists, return a concrete gainful chain in forward conversion order, containing only the loop itself (no lead-in path), and verify that its rate product is greater than 1.

Hints

Hint 1

A chain's total gain is the product of its rates. Which standard transformation turns a product into a sum, and what does 'product greater than 1' become after it?

Hint 2

After taking -log of each rate, you are looking for a negative-weight cycle. Think about which shortest-path algorithm detects that, and how to make it work when the graph is not connected (for example, start every distance at 0).

Hint 3

To recover the loop, store a predecessor for each node when it is relaxed. If a relaxation still succeeds on the V-th pass, walk back V times along predecessors to guarantee you are inside the cycle, then follow predecessors until you return to that node and reverse the result.