Notes
All notes

Linked List (LeetCode #6)

A linked list is a chain of nodes, each holding a value and a next pointer. There is no index, so every trick is pointer bookkeeping — and the most common bug is breaking a link before saving what came after it. Three habits (a dummy node, save-then-flip, and two speeds) solve the eleven NeetCode Linked List problems in this post.

The technique

A node:

class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next

Dummy node. Put a throwaway node before the head and build onto it — it removes the “is this the first node?” special case in merges and deletions.

Save before you break. Before changing curr.next, save the old value — otherwise the rest of the list is unreachable.

Fast and slow pointers. One pointer moves one step, another two. They find the middle, detect cycles, and locate positions.

Reverse Linked List

The question. Reverse the list and return the new head.

Input:  1 -> 2 -> 3 -> null
Output: 3 -> 2 -> 1 -> null

The idea. Walk once, flipping each next backward, using three pointers: prev, curr, nxt.

Walk it through on 1→2→3: prev=None, curr=1; save nxt=2, set 1.next=None; prev=1, curr=2; save 3, 2.next=1; prev=2, curr=3; save None, 3.next=2; prev=3, curr=None → new head 3.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt}]
  \node[n, fill=blue!8] (a) at (0,0) {1}; \node[n, fill=blue!8] (b) at (1.4,0) {2}; \node[n, fill=blue!8] (c) at (2.8,0) {3};
  \draw[->, thick, orange!80!black] (b) -- (a);
  \draw[->, thick, black!40] (a) -- (b);
  \draw[->, thick, black!40] (b) -- (c);
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (0,-0.5) {prev};
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (1.4,-0.5) {curr};
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (2.8,-0.5) {nxt};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.4,-1.0) {save, flip, advance};
\end{tikzpicture}
def reverse_list(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next          # save
        curr.next = prev         # flip
        prev, curr = curr, nxt   # advance
    return prev

\(O(n)\) time, \(O(1)\) space. See Reverse a Linked List.

Merge Two Sorted Lists

The question. Merge two sorted lists into one sorted list.

Input:  a = 1->2->4, b = 1->3->4
Output: 1->1->2->3->4->4

The idea. Compare the two heads, take the smaller, advance that list, repeat. The dummy node handles the first element.

Walk it through on a = 1→2→4, b = 1→3→4:

a b a.val <= b.val? append built list
1 1 yes a’s 1 1
2 1 no b’s 1 1→1
2 3 yes a’s 2 1→1→2
4 3 no b’s 3 1→1→2→3
4 4 yes a’s 4 1→1→2→3→4
None 4 — attach b 1→1→2→3→4→4
def merge_two(a, b):
    dummy = tail = Node(0)
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b            # attach the remainder
    return dummy.next

Why it works. Both inputs are sorted, so the smaller of the two current heads is the smallest unused node overall; taking it is never wrong. When one list runs out, the other is already sorted, so the whole remainder can be attached in one step.

Why the dummy node. It gives the first appended node a prev to hang off, so there is no “is this the first node?” special case. dummy.next is the real head.

Complexity. \(O(m+n)\) time, \(O(1)\) extra space (the lists are relinked, not copied).

Edge cases. Either or both lists empty → the other (or None). Duplicate values are kept (use < instead of <= to prefer b on ties).

Reorder List

The question. Reorder L0→L1→L2→…→Ln into L0→Ln→L1→Ln-1→….

Input:  1->2->3->4  ->  1->4->2->3

The idea. Three moves: find the middle (fast/slow), reverse the second half, then weave the halves.

Walk it through on 1→2→3→4:

  1. Find the middle. slow starts at 1, fast at 2. Step once: slow=2, fast=None. So slow=2 is the middle; cut after it.
  2. Split. First half 1→2→None, second half 3→4.
  3. Reverse the second half. 3→4 becomes 4→3.
  4. Weave the halves 1→2 and 4→3:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt}]
  \node[n, fill=green!15] (a) at (0,0) {1}; \node[n, fill=orange!15] (b) at (1.4,0) {4}; \node[n, fill=green!15] (c) at (2.8,0) {2}; \node[n, fill=orange!15] (d) at (4.2,0) {3};
  \draw[->, thick] (a) -- (b); \draw[->, thick] (b) -- (c); \draw[->, thick] (c) -- (d);
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (0,-0.5) {1st};
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.4,-0.5) {2nd};
\end{tikzpicture}
step first half second half result so far
start 1→2 4→3 —
take 4 1→2 3 1→4
take 2 None 3 1→4→2
take 3 None None 1→4→2→3
def reorder_list(head):
    slow, fast = head, head.next
    while fast and fast.next:            # 1. middle
        slow, fast = slow.next, fast.next.next
    second = slow.next
    slow.next = None                     # cut
    prev = None                          # 2. reverse second half
    while second:
        nxt = second.next
        second.next = prev
        prev, second = second, nxt
    first, second = head, prev
    while second:                        # 3. weave
        first.next, first = second, first.next
        second.next, second = first, second.next

Why fast = head.next. Starting fast one ahead makes slow land on the end of the first half when the length is even, and just before the midpoint when it is odd — exactly the split point we need. If fast started at head, slow would land one node too far right.

Why the weave is safe. The second half is never longer than the first (the middle split guarantees it), so the loop condition while second covers every pair; the last node of the first half is left pointing at None, which is a valid tail.

Complexity. \(O(n)\) time, \(O(1)\) extra space.

Edge cases. Empty list, one node, or two nodes all work: the middle split leaves a second half that is empty or a single node, and the loops handle it without special cases.

Remove Nth Node From End of List

The question. Remove the n-th node from the end and return the head.

Input:  1->2->3->4->5, n = 2  ->  1->2->3->5

The idea. One pass with a fixed gap. Send a fast pointer n steps ahead, then move slow and fast together until fast reaches the end. Now slow is just before the node to remove. A dummy node handles removing the head.

Walk it through on 1->2->3->4->5, n=2: fast moves to 3 (2 steps). Move both: slow=1,fast=4; slow=2,fast=5; slow=3,fast=None. slow(3).next = 4.next = 5. Result 1->2->3->5.

def remove_nth_from_end(head, n):
    dummy = Node(0, head)
    slow = fast = dummy
    for _ in range(n + 1):           # create the gap of n
        fast = fast.next
    while fast:
        slow, fast = slow.next, fast.next
    slow.next = slow.next.next       # unlink
    return dummy.next

\(O(n)\) time, \(O(1)\) space.

Copy List With Random Pointer

The question. Deep-copy a list where each node has a next and a random pointer (which may point anywhere or be None).

Input:  nodes with next and random pointers
Output: an independent copy with the same structure

The idea. Two passes with a map from original → clone. First pass creates every clone and stores the mapping. Second pass wires next and random using the map.

Walk it through. Node A has random → C. After pass 1 the map is {A: A', B: B', C: C'}. In pass 2, A'.random = map[A.random] = C'. Cycles in random are fine because the clones already exist.

def copy_random_list(head):
    clones = {}
    node = head
    while node:                      # 1. create clones
        clones[node] = Node(node.val)
        node = node.next
    node = head
    while node:                      # 2. wire pointers
        clones[node].next = clones.get(node.next)
        clones[node].random = clones.get(node.random)
        node = node.next
    return clones.get(head)

\(O(n)\) time and space.

Add Two Numbers

The question. Two numbers are stored as linked lists in reverse order (ones digit first). Return their sum as a linked list.

Input:  2->4->3  +  5->6->4       (342 + 465)
Output: 7->0->8                   (807)

The idea. Add digit by digit like grade school, carrying over. Walk both lists, sum the digits plus the carry, write sum % 10, and carry sum // 10. Continue while either list has digits or a carry remains.

Walk it through. 2+5=7 (carry 0) → 7. 4+6=10 → write 0, carry 1. 3+4+1=8 → 8. Result 7->0->8.

def add_two_numbers(l1, l2):
    dummy = tail = Node(0)
    carry = 0
    while l1 or l2 or carry:
        a = l1.val if l1 else 0
        b = l2.val if l2 else 0
        total = a + b + carry
        carry = total // 10
        tail.next = Node(total % 10)
        tail = tail.next
        l1 = l1.next if l1 else None
        l2 = l2.next if l2 else None
    return dummy.next

\(O(\max(m,n))\) time, \(O(1)\) extra space (beyond the output).

Linked List Cycle

The question. Return True if the list contains a cycle.

Input:  3->2->0->-4->(back to 2)  -> True

The idea — Floyd’s tortoise and hare. slow one step, fast two. If there is a cycle, the fast pointer catches the slow one; if it reaches None, no cycle.

Walk it through on 3→2→0→-4→(back to 2):

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt}]
  \node[n, fill=blue!8] (a) at (0,0) {3}; \node[n, fill=blue!8] (b) at (1.4,0) {2}; \node[n, fill=blue!8] (c) at (2.8,0) {0}; \node[n, fill=blue!8] (d) at (4.2,0) {-4};
  \draw[->, thick] (a) -- (b); \draw[->, thick] (b) -- (c); \draw[->, thick] (c) -- (d);
  \draw[->, thick, orange!80!black] (d) to[bend right=30] (b);
  \node[font=\scriptsize\ttfamily] at (0.7,-0.55) {slow +1};
  \node[font=\scriptsize\ttfamily] at (2.1,-0.55) {fast +2};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.1,-1.0) {fast laps slow inside the cycle};
\end{tikzpicture}
step slow fast meeting?
0 3 3 —
1 2 0 no
2 0 2 no
3 -4 -4 yes → cycle
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Why they must meet. Once both pointers are inside the cycle, the gap between them (in nodes) shrinks by one each step because fast gains one node on slow. A gap that decreases by one every step must hit zero, so if a cycle exists they collide.

Why \(O(1)\) space. No set of visited nodes is kept; the meeting relies only on the two pointers.

Complexity. \(O(n)\) time (\(O(n)\) steps before the meeting at the latest), \(O(1)\) space.

Edge cases. Empty list or one node → False. A cycle that includes the head is found the same way.

Find the Duplicate Number

The question. An array of n+1 integers, each in 1..n, contains exactly one duplicate (possibly repeated more than twice). Find it without modifying the array and in \(O(1)\) extra space.

Input:  [1,3,4,2,2]  -> 2

The idea — treat the array as a linked list. Because each value is in 1..n, index i points to nums[i]. A duplicate value means two indices point to the same node, which creates a cycle. So the duplicate is the cycle’s entrance, found with Floyd’s algorithm exactly as in Problem 7.

Walk it through on [1,3,4,2,2]: start at 0 → 1 → 3 → 2 → 4 → 2 → 4 …, a cycle entering at 2. Floyd finds the entrance = 2.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt}]
  \node[n, fill=blue!8] (i0) at (0,0) {0}; \node[n, fill=blue!8] (i1) at (1.4,0) {1}; \node[n, fill=blue!8] (i3) at (2.8,0) {3}; \node[n, fill=orange!20] (i2) at (4.2,0) {2}; \node[n, fill=blue!8] (i4) at (5.6,0) {4};
  \draw[->, thick] (i0) -- (i1); \draw[->, thick] (i1) -- (i3); \draw[->, thick] (i3) -- (i2); \draw[->, thick] (i2) -- (i4); \draw[->, thick, orange!80!black] (i4) to[bend right=30] (i2);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.8,-0.55) {index i points at nums[i]; the duplicate is the cycle entrance};
\end{tikzpicture}
def find_duplicate(nums):
    slow = fast = nums[0]
    while True:                          # phase 1: find a meeting point
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    slow = nums[0]                        # phase 2: find the cycle entrance
    while slow != fast:
        slow = nums[slow]
        fast = nums[fast]
    return slow

\(O(n)\) time, \(O(1)\) space.

LRU Cache

The question. Design a Least-Recently-Used cache with get(key) and put(key, value), both \(O(1)\), evicting the least-recently-used key when capacity is exceeded.

capacity 2: put(1,1); put(2,2); get(1)->1; put(3,3) evicts key 2; get(2)->-1

The idea. A hash map alone cannot tell which key is least recent; a list alone cannot find a key in \(O(1)\). Combine them: a hash map from key to node and a doubly linked list ordering by recency. get/put move the node to the front; eviction removes the tail.

Each structure covers the other’s weakness:

To avoid fiddly edge cases, use two sentinel nodes (head, tail); the real nodes live between them, most-recent next to head.

Walk it through with capacity = 2:

operation action list (front = most recent) map keys
put(1,1) add 1 at front 1 {1}
put(2,2) add 2 at front 2, 1 {1,2}
get(1) move 1 to front → 1 1, 2 {1,2}
put(3,3) add 3, size 3 > 2, evict tail.prev = 2 3, 1 {1,3}
get(2) missing → -1 3, 1 {1,3}
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.map = {}
        self.head, self.tail = Node(0), Node(0)
        self.head.next, self.tail.prev = self.tail, self.head
    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev
    def _add_front(self, node):
        node.next = self.head.next
        node.prev = self.head
        self.head.next.prev = node
        self.head.next = node
    def get(self, key):
        if key not in self.map:
            return -1
        node = self.map[key]
        self._remove(node); self._add_front(node)
        return node.val
    def put(self, key, value):
        if key in self.map:
            self._remove(self.map[key])
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)
        if len(self.map) > self.cap:
            lru = self.tail.prev
            self._remove(lru)
            del self.map[lru.key]

Why get must reorder. Returning immediately would leave a recently-read key at the tail, so it could be evicted even though it was just used. Moving it to the front is what makes the recency order correct.

Why put on an existing key works. The old node is removed first, so the new value lands at the front and the size does not grow; no eviction happens on an update.

Complexity. \(O(1)\) per operation (each touches a constant number of nodes), \(O(\text{capacity})\) space.

Edge cases. capacity = 1 evicts the single key on the next insert. Updating an existing key never evicts. The sentinels mean the list is never empty from the code’s point of view, so no None checks are needed in _remove/_add_front.

Merge k Sorted Lists

The question. Merge k sorted lists into one.

Input:  [[1,4,5],[1,3,4],[2,6]]
Output: 1->1->2->3->4->4->5->6

The idea. Put all heads in a min-heap; pop the smallest, append it, push its successor. O(N log k) for N total nodes.

Walk it through on [[1,4,5], [1,3,4], [2,6]]. The heap holds one node per list; after each pop we push that node’s successor:

pop push next from that list heap after built list
1 (list 0) 4 1, 2, 4 1
1 (list 1) 3 2, 3, 4 1, 1
2 (list 2) 6 3, 4, 6 1, 1, 2
3 (list 1) 4 4, 4, 6 1, 1, 2, 3
4 (list 0) 5 4, 5, 6 1, 1, 2, 3, 4
4 (list 1) — 5, 6 1, 1, 2, 3, 4, 4
5 (list 0) — 6 1, 1, 2, 3, 4, 4, 5
6 (list 2) — empty 1, 1, 2, 3, 4, 4, 5, 6
import heapq

def merge_k(lists):
    heap = [(l.val, i, l) for i, l in enumerate(lists) if l]
    heapq.heapify(heap)
    dummy = tail = Node(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next

The index i breaks ties so nodes are never compared directly.

Why a heap. At any moment the next output node is the smallest of the k current heads. A heap keeps those heads ordered, so each extraction and insertion is \(O(\log k)\); with \(N\) nodes total that is \(O(N \log k)\) — far better than merging pairs repeatedly when k is large.

Why the tie-break index. Python’s heap compares tuples element by element; if two values are equal it would try to compare the nodes themselves, which have no ordering. Including the list index i guarantees the comparison stops before reaching the node.

Complexity. \(O(N \log k)\) time and \(O(k)\) extra space for the heap.

Edge cases. Empty input → None; some lists empty → filtered out at construction. Duplicate values are handled by the tie-break.

Reverse Nodes in k-Group

The question. Reverse the list k nodes at a time; leave a trailing group of fewer than k nodes untouched.

Input:  1->2->3->4->5, k = 2  ->  2->1->4->3->5

The idea. Work group by group. For each group, check it has exactly k nodes; if not, stop. Then reverse those k nodes and reconnect the group to the previous group’s tail.

Walk it through on 1->2->3->4->5, k=2: reverse [1,2] → 2->1; reverse [3,4] → 4->3; [5] has fewer than k nodes, left as is.

def reverse_k_group(head, k):
    dummy = Node(0, head)
    group_prev = dummy
    while True:
        kth = group_prev
        for _ in range(k):                 # find the k-th node
            kth = kth.next
            if not kth:
                return dummy.next          # fewer than k left
        group_next = kth.next
        prev, curr = group_next, group_prev.next
        for _ in range(k):                 # reverse the group
            nxt = curr.next
            curr.next = prev
            prev, curr = curr, nxt
        temp = group_prev.next             # old head becomes the group's tail
        group_prev.next = kth
        group_prev = temp
    return dummy.next

\(O(n)\) time, \(O(1)\) extra space.

Pitfalls

QQuestionSelf-check

Why do you need a third pointer to reverse a list? How does Find the Duplicate Number use Floyd’s algorithm?

ASolution

You must save the next node before flipping the current link, or the remainder is unreachable. In an array of n+1 values in 1..n, treating index i as pointing to nums[i] turns a duplicate into a cycle, and the duplicate value is exactly the cycle’s entrance, found with fast/slow pointers.

Next: Trees (LeetCode #7) — recursion over a hierarchy.