Skip to content
LeetQuant
QD01 Data Structures and Algorithms

QD01 · Data Structures and Algorithms · Lesson 6 of 7

Graphs and Shortest Paths

Adjacency lists and matrices, BFS and DFS, topological sort for dependency graphs, Dijkstra with a heap, and Bellman–Ford with −log rates to detect currency arbitrage.

19 min

Objective

Represent a graph appropriately, pick the right search for the question (BFS, DFS, topological order, Dijkstra, Bellman–Ford), state its complexity in VV and EE, and apply Bellman–Ford to the classic quant question: is there an arbitrage cycle in this table of exchange rates?

Representations

Adjacency listAdjacency matrix
SpaceO(V+E)O(V + E)O(V2)O(V^2)
Is there an edge u→vu \to v?O(deg⁡u)O(\deg u), or O(1)O(1) with a set per nodeO(1)O(1)
Iterate neighbours of uuO(deg⁡u)O(\deg u)O(V)O(V)
Best forsparse graphs, almost everythingdense graphs, small VV, all-pairs algorithms

In Python an adjacency list is dict[node, list[node]], or list[(neighbour, weight)] for weighted edges. A matrix of exchange rates among 10 currencies is naturally dense (E=90E = 90), whereas a graph of instruments and their dependencies is sparse.

BFS and DFS

Breadth-first search explores in rings of increasing distance using a queue. In an unweighted graph the first time BFS reaches a node is along a shortest path, so it computes hop distances in O(V+E)O(V + E).

from collections import deque

def bfs_dist(adj, src):
    dist = {src: 0}
    q = deque([src])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:              # mark when enqueued, not when popped
                dist[v] = dist[u] + 1
                q.append(v)
    return dist

adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
print(bfs_dist(adj, "A"))   # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}

Depth-first search goes as deep as possible before backtracking (recursion, or an explicit stack). It is the tool for connectivity, counting components (islands in a grid), and cycle detection in a directed graph: colour nodes white, grey (on the current path) and black (finished); meeting a grey node means a back edge, hence a cycle. Also O(V+E)O(V + E). For deep graphs in Python, use an explicit stack: the default recursion limit is about 1000.

Topological sort

A DAG (directed acyclic graph) of dependencies, such as "the vol surface needs prices and rates; risk needs the vol surface", must be evaluated in an order where every node comes after everything it depends on. Kahn's algorithm: count each node's incoming edges, start with the nodes that have none, and each time you output a node, decrement its successors' counts and release any that reach zero.

from collections import defaultdict, deque

def topo_sort(deps):
    """deps[u] = nodes that need u (edges u -> v)."""
    indeg = defaultdict(int)
    for u in deps:
        for v in deps[u]:
            indeg[v] += 1
    ready = deque(u for u in deps if indeg[u] == 0)
    order = []
    while ready:
        u = ready.popleft()
        order.append(u)
        for v in deps[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                ready.append(v)
    if len(order) < len(deps):
        raise ValueError("cycle: no valid order")
    return order

deps = {"prices": ["returns", "vol_surface"], "returns": ["risk"],
        "rates": ["vol_surface", "risk"], "vol_surface": ["risk"],
        "risk": ["report"], "report": []}
print(topo_sort(deps))
# ['prices', 'rates', 'returns', 'vol_surface', 'risk', 'report']

O(V+E)O(V + E). If some nodes never reach in-degree zero, they lie on or behind a cycle, so no valid order exists, which doubles as a cycle detector. The order is generally not unique; any order consistent with the edges is correct. Build systems, spreadsheet recalculation and pricing graphs all run on this.

Dijkstra's algorithm

With non-negative edge weights, the unsettled node with the smallest tentative distance cannot be improved later: any other route to it passes through a node at least as far away and only adds non-negative weight. Dijkstra repeatedly settles that node and relaxes its edges. A heap finds it; Python's heapq has no decrease-key, so push a fresh entry and skip stale ones on pop (lazy deletion).

import heapq, math

def dijkstra(graph, src):
    """graph[u] = list of (v, weight) with weight >= 0."""
    dist = {src: 0}
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                       # stale entry
        for v, w in graph[u]:
            nd = d + w
            if nd < dist.get(v, math.inf):
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist

g = {"S": [("A", 4), ("B", 1)], "B": [("A", 2), ("C", 5)], "A": [("C", 1)], "C": []}
print(dijkstra(g, "S"))   # {'S': 0, 'A': 3, 'B': 1, 'C': 4}

The direct edge to A costs 4, but S→B→AS \to B \to A costs 3, and then A→CA \to C gives 4, beating S→B→CS \to B \to C at 6. Cost: each edge pushes at most once, so O((V+E)log⁡V)O((V + E) \log V).

Negative edges break it. Take S→AS \to A weight 2, S→BS \to B weight 3, B→AB \to A weight −2-2, A→CA \to C weight 1. Dijkstra settles A at distance 2 before it ever looks at B, and reports C at 3. The true distances are A =3−2=1= 3 - 2 = 1 and C =2= 2. (The lazy-deletion code above happens to repair this small case by expanding A a second time, but in general re-expansion can take exponential time, and the correctness argument no longer holds.) For negative weights use Bellman–Ford; for a DAG, relax edges in topological order, which handles negative weights in O(V+E)O(V + E).

Bellman–Ford and negative cycles

Bellman–Ford relaxes every edge, V−1V - 1 times. A shortest path with no cycles has at most V−1V - 1 edges, and after round ii every shortest path of at most ii edges is correct, so V−1V - 1 rounds suffice: O(VE)O(VE) in total. If a further round still improves some distance, the graph has a negative cycle reachable from the source, because without one nothing could improve.

From arbitrage to negative cycles. Let rabr_{ab} be the units of currency bb one unit of aa buys. A round trip a→b→⋯→aa \to b \to \dots \to a is profitable when the product of the rates exceeds 1. Taking logs turns products into sums, and negating flips the inequality:

∏edgesrab>1  ⟺  ∑edgeslog⁡rab>0  ⟺  ∑edges(−log⁡rab)<0.\prod_{\text{edges}} r_{ab} > 1 \iff \sum_{\text{edges}} \log r_{ab} > 0 \iff \sum_{\text{edges}} \big(-\log r_{ab}\big) < 0 .

So give each edge weight wab=−log⁡rabw_{ab} = -\log r_{ab}: an arbitrage cycle is exactly a negative cycle. Starting every distance at 0 (as if a virtual source had a zero-weight edge to every node) finds a negative cycle anywhere in the graph. To recover it, record predecessors; a node improved in round VV leads back into the cycle after VV predecessor steps.

Worked example

finding a currency cycle

Rates (units received per unit given): USD→EUR 0.92, EUR→USD 1.08, EUR→GBP 0.86, GBP→EUR 1.16, GBP→USD 1.27, USD→GBP 0.78, USD→JPY 150, JPY→USD 0.0066. Is there an arbitrage? Find it with Bellman–Ford.

Show solution

Two-legged round trips first. USD↔EUR gives 0.92×1.08=0.99360.92 \times 1.08 = 0.9936, EUR↔GBP 0.99760.9976, USD↔GBP 0.78×1.27=0.99060.78 \times 1.27 = 0.9906, USD↔JPY 0.990.99: all below 1, as the bid–ask spread guarantees.

Run Bellman–Ford on −log⁡-\log rates.

import math

def find_arbitrage(currencies, rates):
    """rates[(a, b)] = units of b per unit of a. Returns a profitable cycle, or None."""
    idx = {c: i for i, c in enumerate(currencies)}
    n = len(currencies)
    edges = [(idx[a], idx[b], -math.log(r)) for (a, b), r in rates.items()]
    dist, pred = [0.0] * n, [-1] * n       # virtual source: every node at 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v] - 1e-12:
                dist[v], pred[v] = dist[u] + w, u
    for u, v, w in edges:                   # round n: any improvement => negative cycle
        if dist[u] + w < dist[v] - 1e-12:
            pred[v] = u
            x = v
            for _ in range(n):              # step back n times to land on the cycle
                x = pred[x]
            cycle, y = [x], pred[x]
            while y != x:
                cycle.append(y)
                y = pred[y]
            cycle.append(x)
            return [currencies[i] for i in reversed(cycle)]
    return None

rates = {("USD", "EUR"): 0.92, ("EUR", "USD"): 1.08, ("EUR", "GBP"): 0.86,
         ("GBP", "EUR"): 1.16, ("GBP", "USD"): 1.27, ("USD", "GBP"): 0.78,
         ("USD", "JPY"): 150.0, ("JPY", "USD"): 0.0066}
print(find_arbitrage(["USD", "EUR", "GBP", "JPY"], rates))
# ['USD', 'EUR', 'GBP', 'USD']

Check. 0.92×0.86×1.27=1.0048240.92 \times 0.86 \times 1.27 = 1.004824: one dollar becomes about 1.0048 dollars, a 48 basis-point edge before costs. In log terms the cycle weight is −ln⁡1.004824≈−0.00481<0-\ln 1.004824 \approx -0.00481 < 0. The reverse loop, 0.78×1.16×1.08≈0.9770.78 \times 1.16 \times 1.08 \approx 0.977, loses. If GBP→USD were 1.25 instead, the cycle product would be 0.9890.989 and the function would return None.

What to add out loud. The 10−1210^{-12} tolerance stops floating-point noise from reporting fake cycles. Real arbitrage must survive fees, the time to execute each leg and size limits. And with VV currencies and a full rate table, E=V(V−1)E = V(V - 1), so Bellman–Ford is O(V3)O(V^3), which is trivial for a few dozen currencies.

Knowledge check

You need the fewest trades (hops) to convert one asset into another, where every allowed conversion counts as one hop. Which algorithm is the natural choice?

Knowledge check

Why are arbitrage edges weighted by −log⁡r-\log r rather than by rr or log⁡r\log r?

Knowledge check

Kahn's algorithm finishes having output only 7 of a graph's 10 nodes. What can you conclude?

Knowledge check

What is the complexity of Bellman–Ford with V nodes and E edges, including the extra round that detects negative cycles?

Key takeaways

  • Adjacency lists (O(V+E)O(V + E) space) suit sparse graphs; matrices suit dense ones such as a full rate table.
  • BFS gives unweighted shortest paths; DFS gives connectivity and, with grey/black colouring, directed cycle detection; both are O(V+E)O(V + E).
  • Kahn's topological sort orders a dependency DAG in O(V+E)O(V + E) and reports a cycle when nodes are left over.
  • Dijkstra needs non-negative weights and runs in O((V+E)log⁡V)O((V + E) \log V) with a lazy heap; one negative edge can make it wrong.
  • Bellman–Ford is O(VE)O(VE) and detects negative cycles; with weights −log⁡r-\log r, a negative cycle is a currency arbitrage.

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).