PDSA Interactive Book
Week 11

Network Flows, LP & Complexity Classes

Pushing water through pipes, optimising with constraints — and where efficient algorithms run out.

After this chapter you can…
  • compute a max flow with augmenting paths and read off a min cut
  • model bipartite matching as a flow problem
  • describe a linear program and why optima occur at corners
  • explain P, NP, NP-complete and reductions in your own words

Before you start

Cross-check this chapter

The official Week 11 notes were not reachable when this book was assembled, so this chapter is written from the standard treatment of network flows, linear programming and complexity classes. The ideas and algorithms are the usual ones, but check the exact depth, notation and examples against the official PDSA material and lectures.

Flow networks

A flow network is a directed graph with a source s, a sink t and a non-negative capacity c(u, v) on each edge — pipes in a water system, links in a network, roads with vehicle limits. A flow assigns each edge an amount f(u, v) such that:

RuleMeaning
Capacity0 ≤ f(u, v) ≤ c(u, v)
Conservationfor every vertex other than s and t: total flow in = total flow out

The value of a flow is the net amount leaving s. The maximum flow problem asks for a flow of the largest value.

Augmenting paths and the residual graph

Ford–Fulkerson repeatedly finds a path from s to t that still has spare capacity and pushes flow along it. A greedy choice of paths can get stuck short of the optimum, so we allow undoing earlier flow: for each edge u → v carrying f out of capacity c, the residual graph has a forward edge with capacity c − f (room left) and a backward edge v → u with capacity f (flow we may cancel). An augmenting path is any s → t path in the residual graph; push the bottleneck (minimum residual capacity along it).

Python · editable
Expected output: maximum flow value: 19
Edmonds–Karp — augment along shortest paths, edge labels show flow/capacityInteractive
Edmonds–Karp

Choosing the augmenting path with the fewest edges (BFS) guarantees at most O(V·E) augmentations, giving O(V·E²) total time — regardless of the capacity values. Choosing paths arbitrarily can take time proportional to the capacities themselves.

Predict the output

What is the maximum flow through these two edge-disjoint routes?

# two disjoint routes from s to t with capacities 3 and 5 on the bottlenecks
routes = [[7, 3, 9], [5, 6, 8]]
print(sum(min(r) for r in routes))
Check yourself

Why does the residual graph contain backward edges?

Max-flow min-cut theorem

An s–t cut splits the vertices into a set A containing s and the rest B containing t. Its capacity is the total capacity of edges going from A to B. Every flow must cross the cut, so flow value ≤ capacity of any cut.

Max-flow min-cut theorem

The value of a maximum flow equals the capacity of a minimum s–t cut. When Ford–Fulkerson stops (no augmenting path), the set A of vertices reachable from s in the residual graph is a minimum cut.

Python · editable
Expected output: A = [0, 2] cut capacity = 19 max flow = 19
Check yourself

A network has a cut of capacity 14 and a cut of capacity 17. The maximum flow is…

Check yourself

When Edmonds–Karp ends because BFS cannot reach t in the residual graph, the reachable set is…

Applications

Many problems reduce to max flow: bipartite matching (give every edge capacity 1, add a source linked to the left side and a sink linked to the right side — the max flow equals the size of a maximum matching), airline scheduling, image segmentation, baseball elimination, and finding the number of edge-disjoint paths.

Python · editable
Expected output: (3, {'x': 'B', 'y': 'A', 'z': 'C'})

Linear programming

Linear programming (LP) optimises a linear objective subject to linear constraints. Example — a bakery makes x loaves and y cakes: maximise profit 3x + 5y subject to x + 2y ≤ 14 (oven hours), 3x − y ≥ 0, x − y ≤ 2, x, y ≥ 0.

Each constraint cuts the plane with a line, so the feasible region is a convex polygon (in higher dimensions, a polytope). The objective is a family of parallel lines; the best value is reached at a vertex (corner) of the region. The simplex algorithm walks from vertex to vertex improving the objective; interior-point methods cross the inside. Both solve LPs efficiently in practice, and LP is solvable in polynomial time.

Python · editable
Expected output: best profit 38.0 at x=6.0, y=4.0
Linear program — feasible region, corners and the best profit lineInteractive
Integer programming

If variables must be integers (you cannot bake 2.5 cakes), the problem is called an integer linear program (ILP) — and it becomes NP-hard. Rounding the LP answer may not be optimal or even feasible.

Flows are LPs

Maximum flow is a special LP: variables f(u, v), constraints are capacity and conservation, objective is the flow out of s. Shortest paths and matching are LPs too. Remarkably, for these network problems an optimal solution with integer values always exists when capacities are integers.

Check yourself

The optimum of a linear program (if it exists and is bounded) is attained at…

Check yourself

What makes integer programming hard compared with ordinary LP?

Easy and hard problems: P, NP and NP-completeness

Almost every algorithm in this course runs in polynomial time — O(n^k) for some constant k. We call such problems tractable. Others seem to require exponential time. Complexity theory classifies problems, not programs.

ClassInformal meaningExamples
Psolvable in polynomial timesorting, shortest paths, MST, max flow, LP
NPa proposed solution can be checked in polynomial timeeverything in P, plus SAT, Hamiltonian cycle, subset sum, vertex cover
NP-completethe hardest problems in NP: every NP problem reduces to themSAT, 3-SAT, clique, independent set, vertex cover, travelling salesman (decision version)
NP-hardat least as hard as NP-complete (need not be in NP)optimisation versions, e.g. travelling salesman minimisation

Verifying is easier than finding

Given a puzzle (a Sudoku or a subset-sum instance), verifying a claimed answer is quick; discovering one may require searching a huge space. NP is exactly the set of problems whose yes-answers have short, quickly checkable certificates.

Python · editable
Expected output: [4, 5] True

Reductions

Problem A reduces to B (written A ≤ B) if an algorithm for B could be turned, with polynomial extra work, into an algorithm for A. If we have a fast algorithm for B, we get one for A. To show a problem is hard, reduce a known hard problem to it. Example: independent set and vertex cover are complementary — a set S is independent exactly when all other vertices form a vertex cover, so a fast algorithm for one gives a fast algorithm for the other.

Python · editable
Expected output: True True False False
Travelling salesman — greedy versus every possible tourInteractive
P vs NP

Is every problem whose solution can be quickly checked also quickly solvable? Nobody knows — it is the most famous open problem in computer science (and one of the Clay Millennium Prize problems). Almost everyone believes P ≠ NP. If any NP-complete problem had a polynomial-time algorithm, they all would.

What to do with an NP-hard problem

Exact exponential search for small inputs, approximation algorithms with provable guarantees (e.g. vertex cover within a factor 2), heuristics, or special cases that are easier (trees, small parameters).

Check yourself

Which statement correctly describes class NP?

Check yourself

You prove that SAT (NP-complete) reduces to your problem X in polynomial time. This shows X is…

Check yourself

Pick all that are in P (as far as we know).

Chapter challenge — Week 11

…
Check yourself

In a flow network, 'conservation' means…

Predict the output

What does this program print?

# the network drawn in the visualiser: s=0, a=1, b=2, c=3, d=4, t=5
edges = [(0, 1, 10), (0, 2, 10), (1, 2, 2), (1, 3, 4), (1, 4, 8), (2, 4, 9), (4, 3, 6), (3, 5, 10), (4, 5, 10)]
n, s, t = 6, 0, 5

from collections import deque

def max_flow(n, edges, s, t):
    cap = [[0] * n for _ in range(n)]
    for u, v, c in edges:
        cap[u][v] += c
    flow = 0
    while True:
        parent = [-1] * n
        parent[s] = s
        q = deque([s])
        while q and parent[t] == -1:               # BFS in the residual graph
            u = q.popleft()
            for v in range(n):
                if parent[v] == -1 and cap[u][v] > 0:
                    parent[v] = u
                    q.append(v)
        if parent[t] == -1:
            break                                  # no augmenting path left
        # bottleneck along the path
        b, v = float("inf"), t
        while v != s:
            b = min(b, cap[parent[v]][v])
            v = parent[v]
        v = t
        while v != s:
            cap[parent[v]][v] -= b                 # use up forward capacity
            cap[v][parent[v]] += b                 # create backward (undo) capacity
            v = parent[v]
        flow += b
    return flow, cap

value, residual = max_flow(n, edges, s, t)

print(value)
Check yourself

A cut has edges leaving A with capacities 5, 7 and 3. What is the capacity of the cut?

Put in order

One round of Edmonds–Karp.

Check yourself

Which is known to be solvable in polynomial time?

Check yourself

Which statements are true?

Check yourself

In a feasible region of a linear program, the best value of a linear objective occurs at…

Practice on LeetCode

LeetCode has almost no pure max-flow problems, so these are the closest relatives: bipartite structure and NP-hard-flavoured search problems that need pruning. Max-flow practice is linked below.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 6 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Is Graph Bipartite? ↗Mediumthe structure behind bipartite matching
Possible Bipartition ↗Mediumtwo-colouring with constraints
Subsets ↗Medium2ⁿ search space — why brute force explodes
Combination Sum ↗Mediumexponential search with pruning
Partition to K Equal Sum Subsets ↗MediumNP-hard in general; backtracking + pruning
N-Queens ↗Hardconstraint search, a classic hard-search problem

Beyond LeetCode

Key takeaways

  • A flow obeys capacity and conservation constraints; the max flow is found by repeatedly augmenting along s–t paths in the residual graph (Edmonds–Karp: BFS paths, O(V·E²)).
  • Max-flow = min-cut: the best flow equals the capacity of the cheapest s–t cut. Matching and many other problems reduce to flow.
  • Linear programs optimise linear objectives over polytopes; optimum at a corner; polynomial-time solvable. Requiring integers (ILP) makes them NP-hard.
  • P: solvable fast. NP: solutions verifiable fast. NP-complete: hardest in NP — a fast algorithm for one gives one for all. Whether P = NP is open.
  • Reductions transfer hardness: reduce a known hard problem to yours.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.