Currency Arbitrage Detection and Cycle Recovery

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Foreign-exchange venues publish directed spot quotes as (source, target, rate) tuples, where selling 1 unit of currency source yields rate units of currency target. A currency arbitrage loop is a closed walk of directed conversions that begins with 1 unit of some currency, steps through one or more quoted pairs, and returns to that initial currency holding strictly more than 1 unit.

Implement two functions over a batch of quotes:

  1. has_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> bool — Return True if at least one qualifying profitable conversion loop exists anywhere in the market, and False otherwise.
  2. find_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> Optional[List[str]] — Return one qualifying simple conversion loop as currency tickers in execution order [c_0, c_1, ..., c_L] with c_0 == c_L and distinct intermediate currencies c_0, ..., c_{L-1}, or None when no qualifying loop exists.

Your implementation must obey these market and numerical rules:

  • Directed quotes only: A tuple (A, B, r) permits exchanging A into B at multiplier r; never synthesize a reverse trade (B, A, 1 / r) unless (B, A, ...) is explicitly present in quotes.
  • Zero flat fees and best-venue selection: Trades scale linearly for any notional size without fixed per-trade charges. When quotes contains multiple entries for the same directed pair (A, B), always use the largest quoted rate.
  • Per-hop numerical tolerance (margin): To prevent IEEE-754 rounding noise on fair cross-rates from registering as phantom profit, a simple loop of L conversions with best rates r_1, r_2, ..., r_L qualifies only when both r_1 * r_2 * ... * r_L > exp(L * margin) (default DEFAULT_MARGIN = 1e-9) and the true product strictly exceeds 1.0.
  • Whole-market search and clean cycle output: Detect winning loops even in disconnected currency islands that cannot be reached from the first currency in quotes. Any returned list [c_0, c_1, ..., c_0] must contain strictly the simple cycle itself—no entry path leading into the loop and no dead-end tail branching out of it. When multiple loops or cyclic rotations qualify, returning any one of them is valid.
  • Input validation: Raise ValueError if margin is not a strictly positive finite float (0 < margin < inf) or if any quote has a rate that is zero, negative, NaN, or infinite.

Examples

Example 1

quotes = [
    ("CAD", "AUD", 0.80),
    ("AUD", "SGD", 0.95),
    ("SGD", "CAD", 1.40),
    ("AUD", "CAD", 1.20),
    ("SGD", "AUD", 1.02),
    ("CAD", "SGD", 0.70),
]

has_arbitrage(quotes)   # True
find_arbitrage(quotes)  # ["CAD", "AUD", "SGD", "CAD"] (or a cyclic rotation in the same order)

Walk-through: Trading 1 CAD -> 0.80 AUD -> 0.80 * 0.95 = 0.76 SGD -> 0.76 * 1.40 = 1.064 CAD produces a 6.4% gain, easily clearing exp(3 * 1e-9). Every two-leg round trip (0.96, 0.969, 0.98) and the opposite three-leg direction (0.70 * 1.02 * 1.20 = 0.8568) lose money.

Example 2

quotes = [
    ("CHF", "NOK", 12.0),
    ("NOK", "SEK", 0.98),
    ("CHF", "SEK", 11.5),
    ("SEK", "CHF", 0.084),
]

has_arbitrage(quotes)   # False
find_arbitrage(quotes)  # None

Walk-through: Only two directed cycles exist: CHF -> NOK -> SEK -> CHF multiplies to 12.0 * 0.98 * 0.084 = 0.98784 < 1, and CHF -> SEK -> CHF multiplies to 11.5 * 0.084 = 0.966 < 1. Reverse quotes such as SEK -> NOK are absent and cannot be inferred.

Example 3

quotes = [
    ("MXN", "BRL", 0.30),
    ("NZD", "DKK", 4.10),
    ("NZD", "DKK", 4.25),
    ("DKK", "NZD", 0.24),
]

has_arbitrage(quotes)   # True
find_arbitrage(quotes)  # ["NZD", "DKK", "NZD"] (or ["DKK", "NZD", "DKK"])

Walk-through: Although "MXN" appears first and leads only to a dead end "BRL", the separate NZD/DKK island has two quotes for NZD -> DKK. Picking the stronger quote 4.25 gives 4.25 * 0.24 = 1.02 > 1.0, and "MXN"/"BRL" do not appear in the returned cycle.

Constraints

  • 0 <= len(quotes) <= 10^4, with up to several hundred distinct currency tickers.
  • Currency tickers are non-empty strings.
  • Valid rate and margin values are finite floats strictly greater than 0.0 (including extreme positive floats that may approach IEEE-754 exponent bounds); non-positive, NaN, or infinite numbers must raise ValueError.
  • Target time complexity is O(Q + V * E) for Q quotes, V distinct currencies, and E distinct directed pairs.

Step-by-step walkthrough

  1. Pin down the market rules and function contract

    Before writing code, settle every boundary condition in the specification:

    • Directed quotes only: A quote ("CAD", "AUD", 0.80) lets us exchange 1 CAD for 0.80 AUD, and implies nothing about trading AUD back into CAD. Synthesizing a reverse quote 1 / 0.80 = 1.25 ignores dealer spreads and fabricates nonexistent trades.
    • Zero flat fees, linear scaling: Every conversion scales proportionally for any notional size without fixed per-hop charges.
    • Duplicate directed pairs: When several venues quote the same pair src -> dst, retain only the largest rate because a rational trader always picks the highest payout on that leg.
    • Per-hop floating-point margin: Require every leg to clear a small positive margin (default 1e-9) so IEEE-754 log-rounding noise never triggers phantom arbitrage.
    • Clean simple cycle output: Return any simple winning loop [c0, c1, ..., c0] in forward execution order with zero lead-in prefix or trailing branch, or None when none exists.
    • Scale and validation: With V currencies and E unique directed pairs (E <= V^2), an O(V * E) pass comfortably handles hundreds of currencies in Python. Non-positive, NaN, or infinite rates or margins raise ValueError.
  2. Turn rate multiplication into additive edge weights

    Represent each currency as a vertex in a directed graph and each quote (src, dst, rate) as a directed edge src -> dst. Starting with 1 unit of c0 and trading around a loop c0 -> c1 -> ... -> cL = c0 with rates r1, r2, ..., rL produces an ending balance equal to the product r1 * r2 * ... * rL. Arbitrage exists whenever that product exceeds 1.

    Why not enumerate all simple directed cycles and multiply their rates directly? On a dense market of V currencies, the count of simple directed cycles is sum_{k=2..V} C(V, k) * (k - 1)! — already 1.1 million at V = 10 and 2.6 * 10^11 at V = 15.

    Shortest-path algorithms combine edges by addition, not multiplication. Taking the natural logarithm converts products into sums, and negating flips > 0 into < 0:

    r1 * r2 * ... * rL > 1
      <=>  log(r1 * r2 * ... * rL) > log(1) = 0
      <=>  log(r1) + log(r2) + ... + log(rL) > 0
      <=>  (-log(r1)) + (-log(r2)) + ... + (-log(rL)) < 0
    

    Assigning each directed edge u -> v the weight w = -log(rate) turns a winning currency loop into a negative-weight cycle (a closed directed loop whose edge weights sum to less than zero):

    Quotes:   CAD -> AUD (0.80)       AUD -> SGD (0.95)       SGD -> CAD (1.40)
    Weights:  -log(0.80) = +0.2231    -log(0.95) = +0.0513    -log(1.40) = -0.3365
    
    Cycle sum:  0.2231 + 0.0513 - 0.3365 = -0.0620 < 0
    True gain:  0.80 * 0.95 * 1.40 = 1.064 = exp(+0.0620) > 1   (a 6.4% profit!)
    
  3. Filter out floating-point rounding noise with a per-hop margin

    64-bit floating-point logarithms round at roughly 1e-16. Watch what happens on a completely fair, break-even pair 0.80 and 1.25:

    0.80 * 1.25                     ==  1.0            (exact zero profit)
    -log(0.80) + (-log(1.25))       == -5.5511e-17 < 0 (phantom negative cycle!)
    

    Without a numerical buffer, a strict < 0 cycle check would claim CAD -> AUD -> CAD prints free money!

    Adding a small positive margin (1e-9 by default) to every edge weight eliminates rounding false positives:

    weight = -log(rate) + margin
    

    Around a loop of L conversions, the shifted weights sum below 0 if and only if:

    sum(-log(r_i) + margin) < 0   <=>   sum(log(r_i)) > L * margin
                                  <=>   r1 * r2 * ... * rL > exp(L * margin) ≈ 1 + L * 1e-9
    

    Think of margin as a tiny 1e-9 proportional haircut per hop: seven orders of magnitude above 64-bit rounding error (~1e-16), yet five orders of magnitude smaller than one basis point (1e-4 = 0.01%).

  4. Build the currency graph and keep best venue rates

    Graph arrays are cleanest when vertices are indexed 0 .. V - 1 rather than strings. _build_graph validates each rate, assigns integer IDs in order of first appearance, and retains the maximum rate per (src_id, dst_id) pair:

    from typing import Dict, List, Optional, Tuple
    import math
    
    Quote = Tuple[str, str, float]
    DEFAULT_MARGIN = 1e-9
    
    
    def _build_graph(quotes: List[Quote]) -> Tuple[List[str], Dict[Tuple[int, int], float]]:
        """Assign integer IDs 0..V-1 to currencies and keep the highest rate per directed pair."""
        # currency_names: list[str] mapping integer vertex ID -> currency code, e.g. ["CAD", "AUD"]
        currency_names: List[str] = []
        # currency_to_id: dict[str, int] mapping currency code -> integer vertex ID
        currency_to_id: Dict[str, int] = {}
        # best_rate: dict[(src_id, dst_id), float] storing the highest quoted rate per directed edge
        best_rate: Dict[Tuple[int, int], float] = {}
    
        for src, dst, rate in quotes:
            # rate > 0 is also False for NaN, and isfinite rejects +inf.
            if not (rate > 0 and math.isfinite(rate)):
                raise ValueError(
                    f"rate for {src}->{dst} must be a positive finite number, got {rate!r}"
                )
            for code in (src, dst):
                if code not in currency_to_id:
                    currency_to_id[code] = len(currency_names)
                    currency_names.append(code)
    
            directed_pair = (currency_to_id[src], currency_to_id[dst])
            # If multiple venues quote the same directed pair, a trader always takes the highest rate.
            if directed_pair not in best_rate or rate > best_rate[directed_pair]:
                best_rate[directed_pair] = rate
    
        return currency_names, best_rate
    
  5. Find negative cycles across all components with Bellman-Ford

    Dijkstra's algorithm breaks here because -log(rate) is negative whenever rate > 1. Instead we run the Bellman-Ford algorithm, repeatedly relaxing every edge (if dist[u] + weight < dist[v]: dist[v] = dist[u] + weight).

    Watch out for a classic pitfall: textbook Bellman-Ford sets dist[0] = 0 and dist[others] = +inf, which only explores vertices reachable from vertex 0. In Example 3, MXN -> BRL is a dead-end component while NZD <-> DKK forms an isolated profitable island — starting only at MXN would miss NZD <-> DKK completely!

    Initializing dist = [0.0] * num_currencies for every vertex simultaneously acts like attaching a virtual start node S with a 0-weight edge to every currency:

              0       [MXN] ──> [BRL]
            +───>
       [S] ─+         [NZD] ──> [DKK]
            +───>       ^         |
              0         +─────────+   (isolated winning loop still reached from S!)
    

    Every simple path from S traverses at most V - 1 currency edges. When no negative cycle exists, all distances settle within V - 1 passes. If any vertex still drops during pass V, a negative cycle must exist — and if an earlier pass changes nothing, we return None immediately.

  6. Step off any outgoing tail to isolate the cycle

    When pass V lowers dist[last_updated], must last_updated lie on the negative cycle itself? No! Look at what happens when a losing chain branches out of a profitable CAD <-> AUD loop:

       +────── (-0.18) ──────+
       v                     |
     [CAD] ─── (+0.05) ───> [AUD] ──> [SGD] ──> [CHF] ──> [SEK]
       |<─── negative cycle ───>|      |<── outgoing tail ──>|
    

    Each lap around CAD <-> AUD lowers dist[AUD], and that decrease cascades down the tail into SGD, CHF, and SEK. In pass 5, last_updated can be SEK — even though SEK has zero outgoing edges!

    Notice where the predecessor pointers lead (SEK -> CHF -> SGD -> AUD <-> CAD): they walk backward against the trade arrows, straight back into the negative cycle that fed the drop. With V vertices total, stepping backward V times from last_updated is guaranteed (by the pigeonhole principle) to exit any tail and land on a vertex cycle_start inside the cycle.

    From cycle_start, follow predecessor until returning to cycle_start, then .reverse() the list into forward conversion order. Finally, _is_cycle_profitable multiplies the actual quoted rates around the loop to verify a product strictly above 1.0 — falling back to math.frexp (rate = mantissa * 2^exp) if extreme magnitudes like 1e-200 * 1e-200 would underflow 64-bit floats mid-loop:

    from typing import Dict, List, Tuple
    import math
    
    
    def _is_cycle_profitable(
        best_rate: Dict[Tuple[int, int], float], cycle: List[int]
    ) -> bool:
        """Return True if multiplying the quoted rates around `cycle` yields strictly more than 1."""
        product = 1.0
        for i in range(len(cycle) - 1):
            product *= best_rate[(cycle[i], cycle[i + 1])]
    
        # Fast path for normal rates where intermediate multiplication neither underflows nor overflows.
        if 0.0 < product < math.inf:
            return product > 1.0
    
        # Fallback for extreme rates (e.g. 1e-200 * 1e-200 underflows float64 to 0.0 even if later
        # legs multiply by 2e200 * 2e200 = 4.0): track mantissa in [0.5, 1.0) and exact base-2 exponent.
        mantissa = 1.0
        total_exp = 0
        for i in range(len(cycle) - 1):
            rate = best_rate[(cycle[i], cycle[i + 1])]
            rate_mantissa, rate_exp = math.frexp(rate)
            mantissa, step_exp = math.frexp(mantissa * rate_mantissa)
            total_exp += rate_exp + step_exp
    
        return total_exp > 1 or (total_exp == 1 and mantissa > 0.5)
    
  7. Trace Example 1 pass by pass

    Trace the winning three-currency loop from Example 1: [("CAD", "AUD", 0.80), ("AUD", "SGD", 0.95), ("SGD", "CAD", 1.40)]. Here V = 3 (0: CAD, 1: AUD, 2: SGD), with edge weights -log(rate) + 1e-9 approximately +0.2231, +0.0513, and -0.3365:

    Initial:   dist = [CAD:  0.0000, AUD:  0.0000, SGD:  0.0000]   pred = [-1, -1, -1]
    
    Pass 1:
      CAD->AUD: 0 + 0.2231 = 0.2231 (not < 0)
      AUD->SGD: 0 + 0.0513 = 0.0513 (not < 0)
      SGD->CAD: 0 - 0.3365 = -0.3365 < 0  --> dist[CAD] = -0.3365, pred[CAD] = SGD, last_updated = CAD
    
    Pass 2:
      CAD->AUD: -0.3365 + 0.2231 = -0.1133 < 0        --> dist[AUD] = -0.1133, pred[AUD] = CAD
      AUD->SGD: -0.1133 + 0.0513 = -0.0620 < 0        --> dist[SGD] = -0.0620, pred[SGD] = AUD
      SGD->CAD: -0.0620 - 0.3365 = -0.3985 < -0.3365  --> dist[CAD] = -0.3985, pred[CAD] = SGD
    
    Pass 3 (the V-th pass!):
      Every vertex drops by another 0.0620 (the cycle's negative weight); last_updated = CAD
    
    Reconstruct:
      1. Walk V = 3 steps back from CAD: CAD -> SGD -> AUD -> CAD  (cycle_start = CAD)
      2. Collect backward around pred:   [CAD, SGD, AUD, CAD]
      3. Reverse to forward trade order: ["CAD", "AUD", "SGD", "CAD"]
      4. Verify product:                 0.80 * 0.95 * 1.40 = 1.064 > 1.0  (valid!)
    
  8. Complete solution

    Putting _build_graph, _find_negative_cycle, _is_cycle_profitable, find_arbitrage, and has_arbitrage together:

    from typing import Dict, List, Optional, Tuple
    import math
    
    Quote = Tuple[str, str, float]
    
    # A cycle of L conversions counts as profitable only if the product of its rates
    # exceeds exp(L * margin), about 1 + L * 1e-9 with this default.
    DEFAULT_MARGIN = 1e-9
    
    
    def _build_graph(quotes: List[Quote]) -> Tuple[List[str], Dict[Tuple[int, int], float]]:
        """Assign integer IDs 0..V-1 to currencies and keep the highest rate per directed pair."""
        # currency_names: list[str] mapping integer vertex ID -> currency code, e.g. ["CAD", "AUD"]
        currency_names: List[str] = []
        # currency_to_id: dict[str, int] mapping currency code -> integer vertex ID
        currency_to_id: Dict[str, int] = {}
        # best_rate: dict[(src_id, dst_id), float] storing the highest quoted rate per directed edge
        best_rate: Dict[Tuple[int, int], float] = {}
    
        for src, dst, rate in quotes:
            # rate > 0 is also False for NaN, and isfinite rejects +inf.
            if not (rate > 0 and math.isfinite(rate)):
                raise ValueError(
                    f"rate for {src}->{dst} must be a positive finite number, got {rate!r}"
                )
            for code in (src, dst):
                if code not in currency_to_id:
                    currency_to_id[code] = len(currency_names)
                    currency_names.append(code)
    
            directed_pair = (currency_to_id[src], currency_to_id[dst])
            # If multiple venues quote the same directed pair, a trader always takes the highest rate.
            if directed_pair not in best_rate or rate > best_rate[directed_pair]:
                best_rate[directed_pair] = rate
    
        return currency_names, best_rate
    
    
    def _find_negative_cycle(
        num_currencies: int, edges: List[Tuple[int, int, float]]
    ) -> Optional[List[int]]:
        """Run Bellman-Ford from a virtual source; return a negative cycle [v, ..., v] or None."""
        if num_currencies == 0:
            return None
    
        # Starting every vertex at dist = 0.0 acts like adding a virtual source with a 0-weight
        # edge to every currency, so we find negative cycles even in disconnected components.
        dist = [0.0] * num_currencies
        # predecessor[v] stores the vertex u whose edge u -> v most recently lowered dist[v].
        predecessor = [-1] * num_currencies
        last_updated = -1
    
        # Shortest simple paths from the virtual source use at most num_currencies - 1 real edges.
        # Any improvement in round num_currencies proves a negative-weight cycle exists.
        for _ in range(num_currencies):
            last_updated = -1
            for u, v, weight in edges:
                candidate_dist = dist[u] + weight
                if candidate_dist < dist[v]:
                    dist[v] = candidate_dist
                    predecessor[v] = u
                    last_updated = v
            # Early exit: if a full pass changed nothing, no future pass can change anything either.
            if last_updated == -1:
                return None
    
        # Phase 2: Walk backward num_currencies steps from last_updated.
        # Why: last_updated may sit on an outgoing tail fed by the cycle rather than on the cycle
        # itself; across num_currencies steps among num_currencies vertices, we must enter the cycle.
        cycle_start = last_updated
        for _ in range(num_currencies):
            cycle_start = predecessor[cycle_start]
    
        # Phase 3: Trace around the cycle until we return to cycle_start, then reverse so
        # vertices appear in forward conversion order instead of backward predecessor order.
        backward_cycle = [cycle_start]
        curr = predecessor[cycle_start]
        while curr != cycle_start:
            backward_cycle.append(curr)
            curr = predecessor[curr]
        backward_cycle.append(cycle_start)
        backward_cycle.reverse()
        return backward_cycle
    
    
    def _is_cycle_profitable(
        best_rate: Dict[Tuple[int, int], float], cycle: List[int]
    ) -> bool:
        """Return True if multiplying the quoted rates around `cycle` yields strictly more than 1."""
        product = 1.0
        for i in range(len(cycle) - 1):
            product *= best_rate[(cycle[i], cycle[i + 1])]
    
        # Fast path for normal rates where intermediate multiplication neither underflows nor overflows.
        if 0.0 < product < math.inf:
            return product > 1.0
    
        # Fallback for extreme rates (e.g. 1e-200 * 1e-200 underflows float64 to 0.0 even if later
        # legs multiply by 2e200 * 2e200 = 4.0): track mantissa in [0.5, 1.0) and exact base-2 exponent.
        mantissa = 1.0
        total_exp = 0
        for i in range(len(cycle) - 1):
            rate = best_rate[(cycle[i], cycle[i + 1])]
            rate_mantissa, rate_exp = math.frexp(rate)
            mantissa, step_exp = math.frexp(mantissa * rate_mantissa)
            total_exp += rate_exp + step_exp
    
        # Since 0.5 <= mantissa < 1.0, mantissa * 2**total_exp > 1.0 iff total_exp > 1,
        # or total_exp == 1 and 2 * mantissa > 1.0 (i.e. mantissa > 0.5).
        return total_exp > 1 or (total_exp == 1 and mantissa > 0.5)
    
    
    def find_arbitrage(
        quotes: List[Quote], margin: float = DEFAULT_MARGIN
    ) -> Optional[List[str]]:
        """Return a simple winning conversion loop such as ["CAD", "AUD", "SGD", "CAD"], or None."""
        # Reject 0, negatives, NaN, and +inf; with margin == 0, rounded logs of 0.8 and 1.25
        # sum to -5.55e-17 and would falsely report arbitrage on a break-even pair.
        if not (margin > 0 and math.isfinite(margin)):
            raise ValueError("margin must be a positive finite number")
    
        currency_names, best_rate = _build_graph(quotes)
    
        # Convert multiplicative gains (r1 * r2 * ... > exp(L * margin)) into negative-weight cycles:
        # sum(-log(rate) + margin) < 0.
        edges: List[Tuple[int, int, float]] = []
        for (u, v), rate in best_rate.items():
            weight = -math.log(rate) + margin
            edges.append((u, v, weight))
    
        cycle = _find_negative_cycle(len(currency_names), edges)
        if cycle is None:
            return None
    
        # Defense-in-depth check: verify the reconstructed cycle truly multiplies to > 1.0
        # (guards against caller-supplied ultra-tiny margins below float64 log rounding).
        if not _is_cycle_profitable(best_rate, cycle):
            return None
    
        result: List[str] = []
        for vertex_id in cycle:
            result.append(currency_names[vertex_id])
        return result
    
    
    def has_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> bool:
        """Return True iff at least one simple conversion loop clears `margin` and multiplies > 1."""
        return find_arbitrage(quotes, margin) is not None
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine walking past three airport exchange counters where 1 CAD buys 0.80 AUD, 1 AUD buys 0.95 SGD, and 1 SGD buys 1.40 CAD: trading around that triangle turns 1 CAD into 0.80 * 0.95 * 1.40 = 1.064 CAD — 6.4 cents of riskless profit! Because classic shortest-path algorithms add edge costs rather than multiplying exchange rates, we transform each rate r into an additive weight w = -log(r) + margin: since log(a * b) = log(a) + log(b), a loop whose rates multiply past 1 becomes a negative-weight cycle (a closed loop in a directed graph whose edge weights sum below zero). We then run the Bellman-Ford algorithm (a shortest-path method that repeatedly checks every directed edge u -> v to see if routing through u lowers the cost to reach v, an operation called edge relaxation) starting with distance 0 at every currency so isolated currency islands are searched too.

Why do simpler ideas fall short? Enumerating all simple loops and multiplying their rates blows up factorially — just 15 currencies can form over 260 billion directed cycles! Meanwhile, Dijkstra's shortest-path algorithm breaks whenever an edge weight is negative (rate > 1 yields -log(rate) < 0), and running Bellman-Ford on bare -log(rate) without a tolerance fails on floating-point rounding because exact break-even rates like 0.80 and 1.25 have rounded logs summing to -5.55e-17 < 0.

Let's trace Example 1's winning loop CAD -> AUD (0.80), AUD -> SGD (0.95), SGD -> CAD (1.40) with weights +0.2231, +0.0513, and -0.3365:

Start:   dist = [CAD:  0.0000, AUD:  0.0000, SGD:  0.0000]   pred = [-1, -1, -1]
Pass 1:  SGD->CAD lowers CAD to -0.3365                      pred[CAD] = SGD
Pass 2:  CAD->AUD lowers AUD to -0.1133 (pred=CAD), AUD->SGD lowers SGD to -0.0620 (pred=AUD),
         SGD->CAD lowers CAD again to -0.3985 (pred=SGD)
Pass 3:  Distances still drop in pass V=3! Walk back 3 steps from CAD -> lands on CAD,
         trace pred [CAD, SGD, AUD, CAD], reverse -> ["CAD", "AUD", "SGD", "CAD"] (gain 1.064 > 1)

Complexity

Let Q be the number of input quotes, V be the number of distinct currencies, and E be the number of distinct directed currency pairs (E <= min(Q, V^2)).

  • Time: O(Q + V * E). _build_graph scans the Q quotes once using O(1) average dictionary lookups to assign vertex IDs and retain each pair's highest rate; Bellman-Ford then runs at most V passes across all E unique edges (O(V * E)), and stepping backward V times plus reversing the cycle takes O(V). When no arbitrage exists, the early-exit check typically finishes in far fewer than V passes.
  • Space: O(V + E). We store V currency tickers, V slots in dist and predecessor, and E entries in best_rate and edges.

Edge cases

  • Empty quote list or one-way chain (CHF -> NOK -> SEK): No closed loop exists because reverse quotes are never synthesized; Bellman-Ford settles in at most V - 1 passes and returns None.
  • Disconnected profitable island: In Example 3, MXN -> BRL is a dead-end component while NZD <-> DKK makes money; initializing dist = [0.0] * V acts as a virtual source connected to every component, so NZD <-> DKK is still found.
  • Lead-in prefixes and outgoing tails: When CAD <-> AUD is profitable and AUD -> SGD -> CHF -> SEK branches off it, SEK may be the last vertex updated in pass V; walking V steps backward along predecessor steps off the tail and onto CAD <-> AUD before collecting the loop.
  • Duplicate quotes on the same directed pair: _build_graph keeps the maximum rate, matching best-execution venue selection.
  • Consistent fair cross rates (rate(a, b) = price[a] / price[b]): Every cycle's true product is 1.0, and adding margin = 1e-9 per hop prevents 1e-16 log-rounding noise from triggering false positives.
  • Extreme magnitudes (1e-200 and 2e200) or ultra-tiny caller margin: Logs remain moderate (|-log(1e-200)| ≈ 460.5), and _is_cycle_profitable falls back to math.frexp (splitting a float into a normalized [0.5, 1.0) fraction and an exact integer power of 2) so intermediate products like 1e-200 * 1e-200 neither underflow to 0.0 nor falsely pass on +inf.
  • Invalid inputs: Zero, negative, NaN, or infinite rates or margins raise ValueError.

Common mistakes

  • Starting Bellman-Ford from a single vertex (dist[0] = 0, others +inf): Any winning loop unreachable from currency 0 (such as NZD <-> DKK in Example 3) is silently missed.
  • Tracing the loop directly from last_updated without stepping V hops back first: When last_updated sits on an outgoing tail rather than on the cycle itself, while curr != last_updated loops forever inside the cycle and never terminates!
  • Forgetting .reverse() on the predecessor chain: Because predecessor[v] points to where we came from to reach v, following predecessor walks against the conversion arrows — returning the money-losing reverse loop instead of the winning forward order.
  • Using +log(rate) instead of -log(rate) (or zero tolerance): Searching for a negative sum of +log(rate) finds a losing cycle (product < 1), while omitting margin makes break-even pairs like 0.80 and 1.25 register as arbitrage due to rounding.
  • Inventing reciprocal quotes: Treating CAD -> AUD at 0.80 as implying AUD -> CAD at 1.25 ignores dealer spreads and fabricates nonexistent trades.

Alternative approaches

  • Floyd-Warshall all-pairs shortest paths: Maintain a V x V matrix of minimum log-weights in O(V^3) time and O(V^2) space; any dist[i][i] < 0 indicates a negative cycle passing through i. Very concise on dense graphs (E ≈ V^2), though slower than early-exit Bellman-Ford on sparse markets.
  • Queue-based Bellman-Ford (SPFA — Shortest Path Faster Algorithm): Maintain a FIFO queue of vertices whose dist just dropped so only outgoing edges of improved vertices are relaxed, tracking hop counts (hops[v] >= V) to detect cycles. Faster on average, with the same O(V * E) worst case.

Follow-up questions

  • What makes locating the single highest-return simple cycle fundamentally harder than finding an arbitrary winning loop, and what practical workarounds exist? Without size limits you could repeat any winning loop indefinitely, so "highest return" is only well-defined over simple cycles (visiting no currency twice). Finding the simple cycle with the largest rate product (minimum total -log weight) is NP-hard (no known polynomial-time algorithm exists), because giving every edge weight -1 reduces Hamiltonian cycle (whether a cycle visits all V vertices) directly to checking for a cycle of weight -V. In practice, trading desks either compute the cycle with the best geometric-mean return per hop in O(V * E) time via Karp's minimum-mean-cycle algorithm, or cap execution to K <= 4 legs and evaluate bounded-hop walks by dynamic programming in O(K * V * E) time.
  • How does the graph formulation change when venues charge transaction fees or quote separate buy and sell prices? Separate buy and sell quotes (bid/ask spreads, the gap between a dealer's lower buy price and higher sell price) already fit naturally into our directed graph: AUD/CAD quoted at 0.9000 / 0.9004 simply becomes AUD -> CAD at 0.9000 and CAD -> AUD at 1 / 0.9004 = 1.1106. A proportional fee f (such as 0.001 for 0.1%) multiplies the effective rate by (1 - f), which adds -log(1 - f) to that edge's weight with zero algorithmic changes. A flat per-trade fee (like $5) or depth-dependent order-book slippage breaks scale invariance, requiring a fixed starting trade size (or searching over (currency, quantity) states) rather than multiplying unit rates.
  • When exchange rates stream in one tick at a time, how can you incrementally test for new arbitrage without rerunning full Bellman-Ford on every tick? Cache the settled distances from the previous arbitrage-free state as vertex potentials p[v] (baseline offsets satisfying p[u] + w(u, v) - p[v] >= 0 on every edge). When a quote worsens (rate decreases, so w(u, v) grows), no negative cycle can appear and p stays valid in O(1) time. When a quote u -> v improves to w_new, any newly created negative cycle must traverse u -> v, so we run Dijkstra's algorithm from v to u over non-negative reduced weights w'(x, y) = w(x, y) + p[x] - p[y] >= 0 in O(E log V) time and check whether shortest_path(v -> u) + w_new + p[u] - p[v] < 0.
  • Why can a cycle that looks profitable in your market-data feed still lose money when executed on live exchanges? Network latency makes incoming quotes slightly stale (quote staleness), and competing low-latency participants race for the same mispricing so top-of-book liquidity often disappears before your order arrives. Worse, firing a three-leg loop sequentially exposes you to leg risk: leg 1 (CAD -> AUD) fills, and then leg 2 moves against you before executing, leaving you holding unhedged AUD at a loss. Thin order-book depth, dealer "last-look" rejections on indicative FX streams, and venue fees can easily turn a small theoretical edge into a net loss.

Follow-up questions

Similar questions

More Citadel Securities interview questions

All 4 Citadel Securities questions →