Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Maximum flow through a network

Hard · Target 30 minutes · Graphs

A directed network has n nodes numbered 0 to n − 1. Each triple [u, v, c] in edges is an edge from u to v with capacity c; the same pair may appear more than once, and both [u, v, …] and [v, u, …] may be present. Return the maximum flow from source to sink: the largest total that can leave the source when no edge carries more than its capacity and every other node passes on exactly what it receives.

Examples

InputOutputWhy
n = 4, edges = [[0,1,1],[0,2,1],[1,2,1],[1,3,1],[2,3,1]], source = 0, sink = 320 → 1 → 3 and 0 → 2 → 3.
n = 3, edges = [[0,1,5]], source = 0, sink = 20Nothing reaches the sink.
n = 4, edges = [[0,1,3],[0,1,4],[1,3,5],[0,2,2],[2,3,9]], source = 0, sink = 37Parallel edges add up to 7 into node 1, but 1 → 3 carries only 5; 2 more go through node 2.

Constraints

  • 2 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ 1000
  • 1 ≤ c ≤ 10⁶
  • source ≠ sink

Hints

Hint 1

Keep a matrix of residual capacities: res[u][v] starts as the total capacity from u to v (summing parallel edges).

Hint 2

Repeatedly find a path from source to sink with res > 0 on every step, using breadth-first search, and push its bottleneck.

Hint 3

Pushing b along u → v means res[u][v] -= b and res[v][u] += b. The second update is the reverse edge that lets a later path undo this one.

Where people lose marks

  • Forgetting the reverse update res[v][u] += b, which makes the algorithm greedy and wrong.
  • Overwriting rather than adding parallel edges: two edges 0 → 1 of capacity 3 and 4 give 7.
  • Searching depth-first with large capacities: the number of rounds can grow with the size of the flow.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.