NeetCode 150, stage 12: Advanced Graphs

← Graphs · All 150 problems · 1-D Dynamic Programming →

In this stage the edges have a cost, or the problem puts a rule on the path. The question changes from “can I reach the node” to “what is the cheapest way”. You learn five classic algorithms. Each one is a small change to the DFS, the BFS or the heap that you already know.

Garden notes: the Go syntax for this stage.

Problems on this page

Templates to memorize

Template A: Dijkstra with a heap

Signal

The edges have costs that are not negative. The problem asks for the shortest path, the minimum time or the lowest cost from one start node. A variant asks you to make the largest value on the path as small as possible.

// TEMPLATE A: Dijkstra with a heap. adj[v] holds the edges of v as items
// {cost of the edge, neighbour}. It returns the lowest cost from src to
// each node.
// item and minHeap are the types of Template F.
func shortestPaths(adj [][]item, src int) []int {
    dist := make([]int, len(adj))
    for i := range dist {
        dist[i] = -1 // -1 = no final cost yet
    }
    h := &minHeap{{cost: 0, node: src}} // 1. SEED: the start node costs 0
    for h.Len() > 0 {
        cur := heap.Pop(h).(item) // 2. POP the item with the lowest cost
        // 3. SKIP: this node is final, the item is old
        if dist[cur.node] != -1 {
            continue
        }
        // 4. FINAL: the first pop of a node is its lowest cost
        dist[cur.node] = cur.cost
        for _, e := range adj[cur.node] {
            // 5. PUSH the cost of the full path through cur
            if dist[e.node] == -1 {
                heap.Push(h, item{cost: cur.cost + e.cost, node: e.node})
            }
        }
    }
    return dist // -1 stays for a node that src cannot reach
}

The moves are SEED, POP, SKIP, FINAL, then PUSH. The heap can hold many items for one node, and only the first pop of a node counts. This is why the SKIP check is necessary. For the “minimise the maximum” variant, change only the PUSH. The new cost is the larger of the current cost and the cost of the next cell.

Say it

“Dijkstra always finalises the closest node next, and a min-heap gives me that node. Each edge goes into the heap at most once, so it’s O(E log V).”

Template B: Prim with a heap

Signal

The problem asks for the minimum cost to connect all the points, all the cities or all the computers. The answer is a minimum spanning tree.

// TEMPLATE B: Prim with a heap. It returns the cost of the minimum spanning
// tree
// of a connected graph. item and minHeap are the types of Template F.
func spanningTreeCost(adj [][]item) int {
    inTree := make([]bool, len(adj))
    // 1. SEED: start at node 0, and pay 0 for it
    h := &minHeap{{cost: 0, node: 0}}
    total, joined := 0, 0
    for h.Len() > 0 && joined < len(adj) {
        // 2. POP the cheapest edge that leaves the tree
        cur := heap.Pop(h).(item)
        // 3. SKIP: a cheaper edge already connected this node
        if inTree[cur.node] {
            continue
        }
        // 4. JOIN: the node enters the tree, pay for the edge
        inTree[cur.node] = true
        total += cur.cost
        joined++
        for _, e := range adj[cur.node] {
            if !inTree[e.node] {
                // 5. PUSH the cost of the edge only, not of the path
                heap.Push(h, e)
            }
        }
    }
    return total
}

The moves are SEED, POP, SKIP, JOIN, then PUSH. These are the moves of Dijkstra with one difference: the cost that you push. Dijkstra pushes the cost of the full path from the start. Prim pushes the cost of one edge only. If you push the cost of the path, you get a wrong tree.

Say it

“Prim grows one tree from any node and always adds the cheapest edge that leaves the tree. With a heap that’s O(E log V). Here every pair of points is an edge, so E is n squared.”

Template C: Bellman-Ford with a round limit

Signal

The problem asks for the cheapest path with at most k stops, or with a limit on the number of edges. Plain Dijkstra fails here, because the cheapest path to a node can use too many edges.

// TEMPLATE C: Bellman-Ford with a round limit. An edge is [from, to, cost].
// It returns the lowest cost from src to dst with at most maxEdges edges,
// or -1.
func cheapestWithLimit(n int, edges [][]int, src, dst, maxEdges int) int {
    const inf = math.MaxInt32
    dist := make([]int, n)
    for i := range dist {
        dist[i] = inf
    }
    dist[src] = 0
    // 1. ROUND: each path can get one more edge
    for round := 0; round < maxEdges; round++ {
        next := make([]int, n)
        // 2. COPY: read the last round, write the new round
        copy(next, dist)
        for _, e := range edges {
            from, to, cost := e[0], e[1], e[2]
            if dist[from] != inf && dist[from]+cost < next[to] {
                // 3. RELAX: a cheaper path to the node "to"
                next[to] = dist[from] + cost
            }
        }
        dist = next
    }
    if dist[dst] == inf {
        return -1
    }
    return dist[dst]
}

The moves are ROUND, COPY, then RELAX. After round i, the slice holds the lowest cost with at most i edges. A path with k stops has k + 1 edges, so run k + 1 rounds. Read from the slice of the last round and write to the copy. Without the copy, one round can use two edges in a row, and the limit does not hold.

Say it

“K stops means k plus one flights. I relax every edge k plus one times, and each round reads the previous round’s costs from a copy. That’s O(k times E).”

Template D: Hierholzer’s algorithm

Signal

You must use each edge exactly one time: each ticket, each domino or each street. The answer is an Eulerian path.

// TEMPLATE D: Hierholzer's algorithm. It returns a path that uses each edge
// one time.
// adj[v] lists the neighbours of v. Sort each list first if the order is
// important.
func eulerPath(adj map[string][]string, start string) []string {
    path := []string{}
    var visit func(v string)
    visit = func(v string) {
        for len(adj[v]) > 0 {
            next := adj[v][0]
            // 1. USE the edge: remove it before the call
            adj[v] = adj[v][1:]
            visit(next)
        }
        path = append(path, v) // 2. ADD v only after all its edges are used
    }
    visit(start)
    slices.Reverse(path) // 3. REVERSE: the path was built from its end
    return path
}

The moves are USE, ADD, then REVERSE. Add a node to the path only after all its edges are used. So a dead end goes into the path first, and the reverse puts the dead end last. A plain greedy walk fails, because the smallest next node can be a dead end. If the problem wants the smallest path in dictionary order, sort each list of neighbours first.

Say it

“Using every ticket once is an Eulerian path. I run a DFS that removes each edge as it uses it and adds each node in post-order, then I reverse the result. Sorting the destinations first gives the smallest order.”

Template E: Topological sort from comparisons

Signal

The input is a list that is already sorted by a rule that you do not know, and you must find the rule. The input has no edges. You get the edges when you compare adjacent items.

// TEMPLATE E: topological sort built from comparisons. The words are in
// sorted order.
// orderRules returns each rule "x comes before y" as the edge [2]byte{x,
// y}.
func orderRules(words []string) (rules [][2]byte, ok bool) {
    // 1. COMPARE each word with the next word only
    for i := 0; i+1 < len(words); i++ {
        a, b := words[i], words[i+1]
        j := 0
        // 2. SKIP the common prefix
        for j < len(a) && j < len(b) && a[j] == b[j] {
            j++
        }
        if j < len(a) && j < len(b) {
            // 3. EDGE: the first different letters
            rules = append(rules, [2]byte{a[j], b[j]})
        } else if len(a) > len(b) {
            // 4. PREFIX CHECK: "abc" before "ab" is never valid
            return nil, false
        }
    }
    // 5. KAHN: sort the letters with these edges. A cycle is not valid
    return rules, true
}

The moves are COMPARE, SKIP, EDGE, PREFIX CHECK, then KAHN. Compare each word with the next word only. The first different letter gives one rule, and the letters after that position give no rule. Then sort the letters with Kahn’s algorithm, which is Template D on the Graphs page. Two results mean that no order is valid: a longer word before its own prefix, and a cycle in the rules.

Say it

“Each pair of adjacent words gives at most one edge: the first letters that differ. Then it’s a topological sort of at most 26 letters. A cycle, or a word before its own prefix, means the input is invalid.”

Template F: Min-heap of items

Signal

You need the item with the lowest cost many times, and new items arrive during the search. Dijkstra and Prim use this type.

// TEMPLATE F: a min-heap of items for container/heap. Go has no built-in
// priority queue.
// one entry: a node and the cost to get there
type item struct{ cost, node int }
 
// a slice type with the five methods that container/heap needs
type minHeap []item
 
func (h minHeap) Len() int { return len(h) }
 
// lowest cost on top
func (h minHeap) Less(i, j int) bool { return h[i].cost < h[j].cost }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
 
// pointer: the length changes
func (h *minHeap) Push(x any) { *h = append(*h, x.(item)) }
func (h *minHeap) Pop() any {
    old := *h
    // container/heap moves the top item to the end first
    x := old[len(old)-1]
    *h = old[:len(old)-1]
    return x
}
 
// Use the heap with heap.Push(h, x) and heap.Pop(h).(item), never with
// h.Push or h.Pop.
func cheapestNode(items []item) int {
    h := &minHeap{}
    for _, it := range items {
        heap.Push(h, it) // O(log n)
    }
    // O(log n): Pop returns any, so assert the type
    return heap.Pop(h).(item).node
}

The moves are the five methods: LEN, LESS, SWAP, PUSH and POP. The Less method sets the order, so change only Less for a max-heap. The Push and Pop methods have a pointer receiver, because they change the length of the slice. Always call heap.Push(h, x) and heap.Pop(h). A direct call such as h.Push(x) only appends, and the heap order breaks.

Say it

“Go has no built-in priority queue. I define a slice type with Len, Less, Swap, Push and Pop, and container/heap does the rest. Push and pop are O(log n).”

Mistakes in this stage

  • h.Push(x) only appends to the slice. Call heap.Push(h, x) and heap.Pop(h) to keep the heap order.
  • heap.Pop(h) returns any. Add the type assertion: heap.Pop(h).(item).
  • next := dist does not copy a slice, because the two names share one array. Use make and copy.
  • Dijkstra is not correct if an edge has a negative cost. Use Bellman-Ford for such a graph.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

332. Reconstruct Itinerary

LeetCode 332 · Hard

1584. Min Cost to Connect All Points

LeetCode 1584 · Medium

743. Network Delay Time

LeetCode 743 · Medium

778. Swim in Rising Water

LeetCode 778 · Hard

269. Alien Dictionary

LeetCode 269 (premium) · free on NeetCode · Hard

787. Cheapest Flights Within K Stops

LeetCode 787 · Medium


← Graphs · All 150 problems · 1-D Dynamic Programming →