Notes
All notes

Advanced Graphs (LeetCode #12)

Once edges have weights, “fewest hops” is wrong: a two-step path can be cheaper than a one-step one. This post covers the six NeetCode Advanced Graph problems — Dijkstra, Bellman-Ford, minimum spanning trees, priority BFS, Eulerian paths, and topological sort — each explained before the code.

The technique

Dijkstra for non-negative weighted shortest paths: a min-heap keyed by distance; repeatedly take the closest unfinished node and relax its edges.

import heapq

def dijkstra(graph, source):
    dist = {v: float("inf") for v in graph}
    dist[source] = 0
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:              # stale entry
            continue
        for v, w in graph[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(heap, (dist[v], v))
    return dist

Minimum spanning tree (MST) connects all vertices at least total cost: Prim (grow a tree with a heap) or Kruskal (sort edges + union-find).

Reconstruct Itinerary

The question. Use every ticket exactly once starting at "JFK"; return the lexicographically smallest itinerary.

The idea — Hierholzer’s algorithm for an Eulerian path. Follow the smallest available destination until stuck, recording airports, then backtrack; reverse the record.

Walk it through on tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]], start "JFK". Sorted in reverse and pushed, the adjacency lists pop the smallest first: JFK→[MUC], MUC→[LHR], LHR→[SFO], SFO→[SJC].

call ticket taken exhausted → record
visit(JFK) JFK → MUC —
visit(MUC) MUC → LHR —
visit(LHR) LHR → SFO —
visit(SFO) SFO → SJC —
visit(SJC) none left record SJC
back in SFO none left record SFO
… … LHR, MUC, JFK

route = [SJC, SFO, LHR, MUC, JFK], reversed → [JFK, MUC, LHR, SFO, SJC].

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, rounded corners=2pt, minimum width=0.9cm, font=\scriptsize\ttfamily, inner sep=2pt},
  a/.style={->, thick}]
  \node[n] (j) at (0,0) {JFK}; \node[n] (m) at (1.7,0) {MUC}; \node[n] (l) at (3.4,0) {LHR}; \node[n] (s) at (5.1,0) {SFO}; \node[n] (sj) at (6.8,0) {SJC};
  \draw[a] (j) -- (m); \draw[a] (m) -- (l); \draw[a] (l) -- (s); \draw[a] (s) -- (sj);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.4,-0.55) {dead ends record first; reverse at the end};
\end{tikzpicture}
from collections import defaultdict

def find_itinerary(tickets):
    graph = defaultdict(list)
    for src, dst in sorted(tickets, reverse=True):   # pop() gives smallest
        graph[src].append(dst)
    route = []
    def visit(airport):
        while graph[airport]:
            visit(graph[airport].pop())
        route.append(airport)                        # record after exhausting
    visit("JFK")
    return route[::-1]

Why record on the way out. A node is appended only when all its tickets are used, i.e. when the walk is stuck. Stuck positions are dead ends of the Eulerian trail, so they appear at the end of the final path — collecting them post-order and reversing gives forward order. On [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]], the greedy first move JFK→KUL hits a dead end and is recorded first; the final reversal puts it last, yielding [JFK, NRT, JFK, KUL].

Why reverse-sorted plus pop(). Popping from the end is \(O(1)\); since the list was sorted in reverse, the end is the smallest remaining destination, which picks the lexicographically first itinerary among all valid ones.

Complexity. \(O(E \log E)\) time (the sort) and \(O(E)\) space.

Edge cases. Every ticket is used exactly once by construction. "JFK" with no tickets → ["JFK"].

Min Cost to Connect All Points

The question. Connect all points (Manhattan distance) at minimum total cost — an MST on a complete graph.

The idea — Prim. Repeatedly add the cheapest edge from the growing tree to an unvisited point, with a heap of the cheapest distance to each.

Walk it through on points = [[0,0],[2,2],[3,10],[5,2],[7,0]] (answer 20). The heap holds (cheapest known distance, point):

pop seen? total push new distances from here
(0, 0) no → mark 0 (4,1), (13,2), (7,3), (7,4)
(4, 1) no → mark 4 (9,2), (3,3), (7,4)
(3, 3) no → mark 7 (10,2), (4,4)
(4, 4) no → mark 11 (14,2)
(7, 3) etc. stale (seen) 11 skip
(9, 2) no → mark 20 tree complete
def min_cost_connect(points):
    n = len(points)
    seen = [False] * n
    heap = [(0, 0)]
    total = used = 0
    while heap and used < n:
        cost, i = heapq.heappop(heap)
        if seen[i]: continue
        seen[i] = True
        total += cost; used += 1
        for j in range(n):
            if not seen[j]:
                d = abs(points[i][0]-points[j][0]) + abs(points[i][1]-points[j][1])
                heapq.heappush(heap, (d, j))
    return total

Why this builds an MST (cut property). At each step, the seen points and the unseen points form a cut, and the cheapest edge crossing it must belong to every MST. Adding exactly that edge therefore never strays from optimality.

Why stale entries are skipped. A point’s distance is re-pushed every time a closer tree point is found, so the heap carries outdated larger distances; if seen[i]: continue discards both duplicates and worse values.

Complexity. \(O(n^2 \log n)\) time (each of \(n\) rounds scans \(n\) distances into the heap) and \(O(n^2)\) heap space. (Computing all pairwise distances up front is the \(O(n^2)\) memory trap this lazy version avoids.)

Edge cases. One point → 0. Duplicate points connect at cost 0.

Network Delay Time

The question. How long until all nodes receive a signal from k?

The idea. A signal starting at k needs dist(k, v) time to reach v, so every node receives it after the slowest arrival: run Dijkstra from k and take the maximum finite distance. Any infinite distance → -1.

Walk it through on times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2. Dijkstra settles nodes as they pop: (0, 2) → relaxes 1 to 1 and 3 to 1; (1, 1) has no outgoing edges; (1, 3) relaxes 4 to 2; (2, 4) is last. Distances are {2:0, 1:1, 3:1, 4:2}, and the maximum — when the final node 4 hears the signal — is 2.

def network_delay(times, n, k):
    graph = {i: [] for i in range(1, n + 1)}
    for u, v, w in times:
        graph[u].append((v, w))
    dist = dijkstra(graph, k)
    ans = max(dist.values())
    return ans if ans < float("inf") else -1

Why the maximum. Dijkstra gives each node’s earliest arrival; the whole network is done only when the last node hears it, which is the largest of those arrivals.

Complexity. \(O((V+E)\log V)\) time, \(O(V+E)\) space.

Edge cases. One node → 0. An unreachable node → -1. A start node with no edges reaches only itself.

Swim in Rising Water

The question. Move across a grid; the cost of a path is the maximum elevation along it. Minimise that maximum from the top-left to the bottom-right.

The idea — priority BFS (Dijkstra with max). A min-heap keyed by the running maximum; expand the cheapest frontier; the first time the destination is popped, its key is the answer.

Walk it through on the classic grid

[[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]

The pops go 0, 1, 2, 3, 4, 5 along the top row and right column — the key max(t, height) never exceeds 5 while descending — until (2,4) = 16, which raises the key to 16. From there the rest of the path (15, 14, …, 6) is all downhill, so the key stays 16 and the destination (4,4) pops with 16, the answer. Any path avoiding (2,4) would detour through 17+ cells, so 16 is minimal.

def swim_in_water(grid):
    n = len(grid)
    seen = {(0, 0)}
    heap = [(grid[0][0], 0, 0)]
    while heap:
        t, r, c = heapq.heappop(heap)
        if (r, c) == (n - 1, n - 1):
            return t
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            nr, nc = r+dr, c+dc
            if 0 <= nr < n and 0 <= nc < n and (nr, nc) not in seen:
                seen.add((nr, nc))
                heapq.heappush(heap, (max(t, grid[nr][nc]), nr, nc))

Why popping the destination ends it. The heap always expands the frontier with the smallest running maximum, so the first time the destination pops, no other frontier can lead to a smaller maximum — the Dijkstra argument with max in place of +.

Why mark on push. A cell enters the heap once, so the seen check blocks re-insertion and the loop expands each cell at most once.

Complexity. \(O(n^2 \log n)\) time and \(O(n^2)\) space.

Edge cases. A \(1 \times 1\) grid returns its own elevation. Strictly increasing grids force the key up the whole way.

Alien Dictionary

The question. Given a sorted list of words in an unknown alphabet, derive a valid ordering of the letters. Return "" if the order is invalid (a cycle or a bad prefix).

Input:  ["wrt","wrf","er","ett","rftt"]
Output: "wertf"

The idea. Compare adjacent words: at the first differing character, word[i] comes before word[j], which is a directed edge. Build the graph and topologically sort the letters. Two invalid cases: a word is a prefix of the previous one but longer (e.g. "abc" before "ab"), or the graph has a cycle.

Walk it through. wrt < wrf → t → f. wrf < er → w → e. er < ett → r → t. ett < rftt → e → r. Topological order: w, e, r, t, f.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.55cm, font=\small\ttfamily, inner sep=0pt},
  a/.style={->, thick}]
  \node[n] (w) at (0,0) {w}; \node[n] (e) at (1.4,0) {e}; \node[n] (r) at (2.8,0) {r}; \node[n] (t) at (4.2,0) {t}; \node[n] (f) at (5.6,0) {f};
  \draw[a] (w) to[bend left=20] (e); \draw[a] (e) to[bend left=20] (r); \draw[a] (r) to[bend left=20] (t); \draw[a] (t) to[bend left=20] (f);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.8,-0.7) {adjacent words -> letter edges -> topo order};
\end{tikzpicture}
from collections import defaultdict, deque

def alien_order(words):
    graph = {c: set() for w in words for c in w}
    indegree = {c: 0 for c in graph}
    for a, b in zip(words, words[1:]):
        if len(a) > len(b) and a.startswith(b):
            return ""                        # "abc" before "ab" -> invalid
        for ca, cb in zip(a, b):
            if ca != cb:
                if cb not in graph[ca]:
                    graph[ca].add(cb); indegree[cb] += 1
                break
    q = deque([c for c in indegree if indegree[c] == 0])
    order = []
    while q:
        c = q.popleft(); order.append(c)
        for nb in graph[c]:
            indegree[nb] -= 1
            if indegree[nb] == 0: q.append(nb)
    return "".join(order) if len(order) == len(graph) else ""   # cycle -> ""

\(O(C)\) over all characters.

Cheapest Flights Within K Stops

The question. Cheapest price from src to dst using at most k stops (edges).

Why Dijkstra fails. It finds the globally cheapest path but ignores the edge count; a cheap-but-long path is invalid. Use Bellman-Ford for exactly k+1 rounds, relaxing from a copy each round so one round adds one edge.

Walk it through on n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1. Two rounds allow two edges:

round dist before relaxations from it dist after
init [0, ∞, ∞, ∞] — [0, ∞, ∞, ∞]
1 from [0, ∞, ∞, ∞] 0→1 = 100 [0, 100, ∞, ∞]
2 from [0, 100, ∞, ∞] 1→2 = 200, 1→3 = 700 [0, 100, 200, 700]

Answer 700 (0→1→3). The cheaper two-stop path 0→1→2→3 needs three edges, so round 2’s update to node 2 is not usable until a third round — that is exactly the k limit enforced.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt},
  a/.style={->, thick}]
  \node[n] (z) at (0,0) {0}; \node[n] (o) at (1.8,0) {1}; \node[n] (t) at (3.6,0) {2}; \node[n] (th) at (5.4,0) {3};
  \draw[a] (z) -- node[font=\tiny\ttfamily, above] {100} (o);
  \draw[a] (o) -- node[font=\tiny\ttfamily, above] {100} (t);
  \draw[a] (t) -- node[font=\tiny\ttfamily, above] {200} (th);
  \draw[a, orange!80!black] (o) to[bend left=30] node[font=\tiny\ttfamily, above] {600} (th);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.7,-0.55) {round i reaches i edges out -- the copy enforces it};
\end{tikzpicture}
def find_cheapest(n, flights, src, dst, k):
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):
        nxt = dist[:]                      # relax only from the previous round
        for u, v, w in flights:
            if dist[u] + w < nxt[v]:
                nxt[v] = dist[u] + w
        dist = nxt
    return dist[dst] if dist[dst] < INF else -1

Why the copy. Reading from dist while writing into nxt freezes each round’s knowledge: round i computes paths of at most i edges. Without the copy, a single round could chain 0→1→2→3 and smuggle three edges into one round.

Why k+1 rounds. k stops means k+1 flights (edges), and round i permits at most i edges.

Complexity. \(O(k \cdot E)\) time, \(O(n)\) space.

Edge cases. No route within k stops → -1. src == dst → 0. Negative-free prices are assumed (a negative cycle would need a different check).

Pitfalls

QQuestionSelf-check

Why does plain Dijkstra break for K stops, and how does Bellman-Ford fix it? Why does Alien Dictionary use topological sort?

ASolution

Dijkstra ignores the edge count, so it can pick a cheap path with too many edges; relaxing at most K+1 rounds (each from a copy) bounds the edges used. Each pair of adjacent words gives one ordering constraint between two letters, which forms a directed graph whose topological order is a valid alphabet — and a cycle means the input is inconsistent.

Next: 1-D Dynamic Programming (LeetCode #13) — remember the small answers.