NeetCode 150, stage 6: Linked List

← Binary Search · All 150 problems · Trees →

A linked list has no index, so each problem here is about pointers: which pointer to save, which pointer to change, and in which order. This stage trains those pointer moves in Go, where nil is the end of a list. Draw the nodes and the arrows on paper before you write the code.

Garden notes: the Go syntax for this stage.

Problems on this page

#ProblemLevelPatternTemplate
1206. Reverse Linked ListEasyReverse the pointers in placeA: Reverse a list
221. Merge Two Sorted ListsEasyDummy head and mergeB: Dummy head
3143. Reorder ListMediumMiddle, reverse, then weaveC: Fast and slow pointers, A: Reverse a list
419. Remove Nth Node From End of ListMediumDummy head, two pointers with a gapB: Dummy head, C: Fast and slow pointers
5138. Copy List with Random PointerMediumHash map from old node to copyF: Map from old node to new node
62. Add Two NumbersMediumDummy head with a carryB: Dummy head
7141. Linked List CycleEasyFast and slow pointersC: Fast and slow pointers
8287. Find the Duplicate NumberMediumFloyd’s cycle start on indexesC: Fast and slow pointers
9146. LRU CacheMediumHash map plus doubly linked listD: Hash map plus doubly linked list
1023. Merge k Sorted ListsHardMin-heap of list headsE: Heap of nodes, B: Dummy head
1125. Reverse Nodes in k-GroupHardReverse one group at a timeA: Reverse a list, B: Dummy head

Templates to memorize

Template A: Reverse a list

Signal

The problem says reverse, or it needs the nodes from the back: “reorder”, “palindrome”, “groups of k”. The space limit is O(1), so a copy into a slice is not permitted.

// TEMPLATE A: reverse a list in place. Four moves for each node.
func reverse(head *ListNode) *ListNode {
    var prev *ListNode // nil: the old head becomes the tail
    cur := head
    for cur != nil {
        next := cur.Next // 1. SAVE the rest of the list
        cur.Next = prev  // 2. TURN the pointer back
        prev = cur       // 3. MOVE prev
        cur = next       // 4. MOVE cur
    }
    return prev // cur is nil here, and prev is the new head
}

The moves are SAVE, TURN, MOVE, MOVE. Save cur.Next before you turn the pointer, because the turn loses the rest of the list. Return prev, not cur: cur is nil when the loop stops.

Say it

“I reverse the pointers in one pass with three variables: prev, cur and next. That is O(n) time and O(1) space.”

Template B: Dummy head

Signal

The solution builds a new list, or it can remove the first node. For example: merge, add, remove, partition.

// TEMPLATE B: dummy head. Build a list with no special case for the first
// node.
func mergeSorted(a, b *ListNode) *ListNode {
    dummy := &ListNode{} // DUMMY: a node before the real head
    tail := dummy        // the last node of the result
    for a != nil && b != nil {
        if a.Val <= b.Val { // CHOOSE the smaller front node
            tail.Next = a // LINK it after the tail
            a = a.Next
        } else {
            tail.Next = b
            b = b.Next
        }
        tail = tail.Next // ADVANCE the tail
    }
    if a != nil { // LINK THE REST: one list can have nodes left
        tail.Next = a
    } else {
        tail.Next = b
    }
    return dummy.Next // the real head is after the dummy
}

The moves are DUMMY, LINK, ADVANCE, then return dummy.Next. The dummy node gives each real node a node before it, so the first node is not a special case. Advance the tail after each link, or the next link replaces the node that you added.

Say it

“I put a dummy node before the head, so I never need a special case for the first node. At the end I return dummy.Next.”

Template C: Fast and slow pointers

Signal

The problem asks for the middle, a cycle, the start of a cycle or the nth node from the end. It also wants O(1) space, so a set of the nodes that you saw is not permitted.

// TEMPLATE C: fast and slow pointers. fast moves two steps, slow moves one
// step.
func middle(head *ListNode) *ListNode {
    slow, fast := head, head
    for fast != nil && fast.Next != nil { // CHECK two nodes before the jump
        slow = slow.Next      // STEP 1
        fast = fast.Next.Next // STEP 2
    }
    // STOP: the middle (the second middle when the length is even)
    return slow
}
 
// cycleStart returns the node where the cycle starts, or nil (Floyd's
// algorithm).
func cycleStart(head *ListNode) *ListNode {
    slow, fast := head, head
    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
        if slow == fast { // MEET: the two pointers are in a cycle
            p := head // RESTART one pointer from the head
            // both move one step, and they meet at the start
            for p != slow {
                p = p.Next
                slow = slow.Next
            }
            return p
        }
    }
    return nil // fast found the end, so there is no cycle
}

The moves are STEP 1 for the slow pointer and STEP 2 for the fast pointer, then MEET or STOP. Test fast != nil && fast.Next != nil before each jump, in that order, or the code panics on nil. To find the start of a cycle, restart one pointer from the head after the two pointers meet. A related form puts the fast pointer n nodes ahead, then moves the two pointers at the same speed.

Say it

“The fast pointer moves two steps and the slow pointer moves one. If there is a cycle they must meet. If there is none, the fast pointer reaches the end. O(n) time, O(1) space.”

Template D: Hash map plus doubly linked list

Signal

A design problem wants get and put in O(1), and it also needs an order: least recently used, oldest first, newest first.

// TEMPLATE D: hash map plus doubly linked list. The map finds a node in
// O(1).
// The list keeps the order. Two sentinel nodes remove all the nil tests.
type dnode struct {
    key, val   int
    prev, next *dnode
}
 
type orderedMap struct {
    nodes map[int]*dnode // key -> its node in the list
    // SENTINELS: head.next is the newest, tail.prev is the oldest
    head, tail *dnode
}
 
func newOrderedMap() *orderedMap {
    m := &orderedMap{nodes: map[int]*dnode{}, head: &dnode{}, tail: &dnode{}}
    m.head.next = m.tail // an empty list is head <-> tail
    m.tail.prev = m.head
    return m
}
 
// unlink removes n from the list: its two neighbors skip it.
func (m *orderedMap) unlink(n *dnode) {
    n.prev.next = n.next
    n.next.prev = n.prev
}
 
// pushFront puts n after the head sentinel. Set the pointers of n first.
func (m *orderedMap) pushFront(n *dnode) {
    n.prev = m.head
    n.next = m.head.next
    m.head.next.prev = n
    m.head.next = n
}

The moves are FIND the node in the map, UNLINK it, and PUSH it to the front. The map gives the node in O(1), and the two pointers of the node let you remove it in O(1). With the two sentinel nodes, each real node always has a neighbor on each side. Keep the key in the node, because an eviction must also delete the key from the map.

Say it

“A hash map gives me the node in O(1), and a doubly linked list keeps the order of use. So get and put are both O(1).”

Template E: Heap of nodes

Signal

The problem gives k sorted lists or k sorted streams and asks for one sorted result. At each step you need the smallest of k front items.

// TEMPLATE E: a min-heap of list nodes. The top is always the smallest
// front node.
type minHeap []*ListNode
 
func (h minHeap) Len() int { return len(h) }
 
// smallest on top
func (h minHeap) Less(i, j int) bool { return h[i].Val < h[j].Val }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any)        { *h = append(*h, x.(*ListNode)) }
func (h *minHeap) Pop() any {
    old := *h
    last := old[len(old)-1] // container/heap moves the top to the end first
    *h = old[:len(old)-1]
    return last
}
 
func valuesInOrder(lists []*ListNode) []int {
    h := &minHeap{}
    for _, node := range lists {
        if node != nil {
            heap.Push(h, node) // 1. SEED: the head of each list
        }
    }
    var res []int
    for h.Len() > 0 {
        node := heap.Pop(h).(*ListNode) // 2. POP the smallest node
        res = append(res, node.Val)
        if node.Next != nil {
            heap.Push(h, node.Next) // 3. PUSH the node after it
        }
    }
    return res
}

The moves are SEED the heap with the head of each list, POP the smallest node, and PUSH the node after it. The heap holds k nodes at most, so each operation costs O(log k). Do not push a nil node, because Less reads Val and the code panics.

Say it

“I keep the head of each list in a min-heap. I pop the smallest node and push the node after it, so the total is O(N log k).”

Template F: Map from old node to new node

Signal

The problem says deep copy or clone, and a node has an extra pointer that can go to any other node.

// TEMPLATE F: copy linked nodes with a map from each old node to its copy.
func deepCopy(head *Node) *Node {
    copyOf := make(map[*Node]*Node) // old node -> new node
    for cur := head; cur != nil; cur = cur.Next {
        // PASS 1: CREATE each copy, with no links
        copyOf[cur] = &Node{Val: cur.Val}
    }
    for cur := head; cur != nil; cur = cur.Next {
        // PASS 2: LINK through the map
        copyOf[cur].Next = copyOf[cur.Next]
        // a nil key is not in the map: the result is nil
        copyOf[cur].Random = copyOf[cur.Random]
    }
    return copyOf[head]
}

The moves are CREATE all the copies in the first pass, then LINK them in the second pass. The map answers one question: where is the copy of this node? Do not point a copy to an old node. Each pointer of a copy must come from the map.

Say it

“I make every copy first and keep a map from each original node to its copy. The second pass sets next and random through the map, so it is O(n) time and O(n) space.”

Mistakes in this stage

  • fast.Next.Next panics when fast.Next is nil. Test fast != nil && fast.Next != nil first.
  • Save cur.Next before the turn. If not, you lose the rest of the list.
  • var dummy *ListNode is a nil pointer, and dummy.Next panics. Write dummy := &ListNode{}.
  • == on two *ListNode values compares the addresses. It does not compare Val.

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.

206. Reverse Linked List

LeetCode 206 · Easy

21. Merge Two Sorted Lists

LeetCode 21 · Easy

143. Reorder List

LeetCode 143 · Medium

19. Remove Nth Node From End of List

LeetCode 19 · Medium

138. Copy List with Random Pointer

LeetCode 138 · Medium

2. Add Two Numbers

LeetCode 2 · Medium

141. Linked List Cycle

LeetCode 141 · Easy

287. Find the Duplicate Number

LeetCode 287 · Medium

146. LRU Cache

LeetCode 146 · Medium

23. Merge k Sorted Lists

LeetCode 23 · Hard

25. Reverse Nodes in k-Group

LeetCode 25 · Hard


← Binary Search · All 150 problems · Trees →