Skip to contentKEEP THE CRAFTTHE SANCTUARY

Linked List

Follow a linked chain through next references, then change only the edges you own. Preserve the untouched successor before relinking, return the new head when it moves, and distinguish an O(1) local edit from locating or copying nodes.

2 practice exercises16 interview problems

Recognize it when The input is already a node chain and the answer depends on relinking it.

Checking your account…

Linked List Code Labs

Mental Model

A linked list stores order in references, not in adjacent array positions. A node owns a value and a next reference; the head is the only external entry point required to reach the chain. There is no constant-time list[index] operation. To reach the kth node, follow k links.

In the Labs, an integer array represents those references: next_indices[node] is the next node or -1. The representation makes pointer changes observable without hiding the central ownership rule inside a helper class. These Labs assume valid indices and a finite acyclic chain; the sentinel bypass also assumes its removal target is reachable from the head. A cyclic chain needs a separate cycle-detection contract before this traversal can terminate.

Nodes, References, and Ownership

Python variables hold references to node objects. Two names may alias the same node, so changing node.next is visible through every alias. Reassigning the local variable node only moves that one cursor; it does not change the chain.

The key question before mutation is: which reference owns the edge being replaced? Removing a node means updating its predecessor’s next, or updating the external head when there is no predecessor.

Traverse Without Random Access

Start at the head and repeatedly follow next. Before each step, the output contains exactly the nodes already visited in chain order, and the cursor names the next unvisited node. This scan is O(n) time and O(1) auxiliary space when it only aggregates; materializing visited values costs O(n) output space.

Follow a Linked Chain

Reference
def chain_order(next_indices, head):
    order = []
    current = head
    while current != -1:
        order.append(current)
        current = next_indices[current]
    return order
Practice

Implement chain_order(next_indices, head). Follow next references from head until -1 and return the visited node indices in chain order. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain.

Public tests

  • Verify reference order wins
  • Verify empty head boundary

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Follow a Linked Chain

def chain_order(next_indices, head):
    order = []
    current = head
    while current != -1:
        order.append(current)
        current = next_indices[current]
    return order

Pointer updates must preserve the successor before overwriting the edge that reaches it. During reversal, keep three meanings stable: previous is the reversed prefix head, current is the next node to move, and successor preserves the untouched suffix. Then redirect current.next, advance both boundaries, and repeat.

Reverse Links Safely

Reference
def reverse_chain(next_indices, head):
    links = next_indices.copy()
    previous = -1
    current = head
    while current != -1:
        successor = links[current]
        links[current] = previous
        previous = current
        current = successor
    return links, previous
Practice

Implement reverse_chain(next_indices, head). Return a copied next-index array and the new head after reversing only the reachable chain. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain.

Public tests

  • Verify successor preservation
  • Verify input links stay unchanged

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Reverse Links Safely

def reverse_chain(next_indices, head):
    links = next_indices.copy()
    previous = -1
    current = head
    while current != -1:
        successor = links[current]
        links[current] = previous
        previous = current
        current = successor
    return links, previous

Trace Successor Preservation During Reversal

Use the reversal Lab on links [1, 2, -1] with head 0. The saved successor keeps the unreversed suffix reachable while each edge turns backward. The function copies its link array, so it returns both the new storage and a new head.

print(reverse_chain([1, 2, -1], 0)) followed by print(reverse_chain([], -1))

Step Executed statement State Why
1 links = next_indices.copy(); previous = -1; current = head links = [1, 2, -1]; previous = -1; current = 0 A copied array preserves input ownership; no node has moved yet.
2 successor = links[current]; links[current] = previous successor = 1; links = [-1, 2, -1] Save node 1 before overwriting the edge that reaches it.
3 previous = current; current = successor previous = 0; current = 1 The reversed prefix grows by one while the untouched suffix remains reachable.
4 successor = links[current]; links[current] = previous; previous = current; current = successor links = [-1, 0, -1]; previous = 1; current = 2 Node 1 now reaches the already reversed prefix; saved successor advances to node 2.
5 successor = links[current]; links[current] = previous; previous = current; current = successor links = [-1, 0, 1]; previous = 2; current = -1 The end marker terminates traversal and previous is the new entry point.
6 return links, previous result = ([-1, 0, 1], 2) Both the changed edges and the head are needed to describe the reversed chain.
Print Output
1 ([-1, 0, 1], 2)
2 ([], -1)

After the last iteration, previous names node 2 and current reaches -1. Returning the old head 0 would expose only the former first node. Copying is part of this Lab’s ownership contract and costs linear space even though the pointer transition uses only a few cursors.

If successor is read after the redirect, the original suffix is no longer reachable from the cursor. This is the linked-list version of overwriting data before saving it.

Use a Sentinel for Head Boundaries

A sentinel is a temporary predecessor whose next points at the real head. It lets deletion use the same “predecessor skips target” transition even when the target is currently first. Return the sentinel’s updated successor as the new head; the sentinel itself is not part of the result.

Bypass a Node through a Sentinel

Reference
def bypass_node(next_indices, head, remove_index):
    sentinel = len(next_indices)
    links = next_indices.copy() + [head]
    predecessor = sentinel
    while links[predecessor] != remove_index:
        predecessor = links[predecessor]
    links[predecessor] = links[remove_index]
    return links[:-1], links[sentinel]
Practice

Implement bypass_node(next_indices, head, remove_index). Use a temporary sentinel predecessor and return copied links plus the possibly changed head. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain. remove_index is a valid node reachable from head.

Public tests

  • Verify middle-node bypass
  • Verify sentinel head update

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Bypass a Node through a Sentinel

def bypass_node(next_indices, head, remove_index):
    sentinel = len(next_indices)
    links = next_indices.copy() + [head]
    predecessor = sentinel
    while links[predecessor] != remove_index:
        predecessor = links[predecessor]
    links[predecessor] = links[remove_index]
    return links[:-1], links[sentinel]

Sentinels simplify control flow but do not remove the need for a contract. Decide whether the target is guaranteed to exist and whether the removed node must be detached for memory or API semantics.

Choose a Linked List or Another Structure

Choose a linked list when the input is already node-based and the task depends on local relinking, streaming merge, or constant-space reversal. Choose a Python list when indexed access dominates; its compact built-in representation is usually faster and simpler. Choose a deque for an ordinary queue instead of manually maintaining nodes.

Linked lists do not make arbitrary deletion O(1) unless the operation already owns the predecessor or the node contract provides enough local references. Searching for the deletion point remains O(n).

Linked Reference and Head Mistakes

  • Advancing before saving the successor can lose the rest of the chain.
  • Returning the old head after reversal exposes only the former first node.
  • Comparing node values instead of node identity can break problems with duplicate values.
  • Mutating a shared input when the function promises a new chain violates alias expectations.
  • Forgetting an empty head or one-node chain often produces an attribute error or stale reference.

Explain It in an Interview

Name each cursor by meaning before coding: predecessor, current, successor, or sentinel. State which part of the chain is already final and which edge still connects to untouched nodes. Draw one three-node example, then verify the empty and head-changing cases. Complexity follows from how many times each link is visited; pointer assignment is constant time, but locating a node may require a full traversal.

Relink Nodes Safely(opens in a new tab) isolates one edge replacement. Add Two Numbers(opens in a new tab) adds synchronized traversal, carry state, unequal lengths, and result ownership.

Templates To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Dummy head for building a list

Head might change? Start from a dummy.

You build, merge, or delete nodes and the head itself might change.

Trigger words

  • merge two sorted lists
  • remove nth node
  • delete nodes
  • partition list
  • head may change
  • add two numbers
def merge_two_lists(list1, list2):
    dummy = ListNode()
    tail = dummy
    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next
    if list1:
        tail.next = list1
    else:
        tail.next = list2
    return dummy.next

Spot it when

  • Merge sorted lists.
  • Remove nodes, partition a list.

Remember

  • tail is always the last node of the answer so far.
  • Return dummy.next, never dummy.

How problems bend it

  • Remove the n-th node from the end: Start two pointers at the dummy, move one n + 1 steps ahead, then move both.
  • Add two numbers: Same tail-building loop, plus a carry.

Reverse a linked list

Save next, point back, step forward.

You need a list (or part of it) in reverse order without extra space.

Trigger words

  • reverse a linked list
  • reverse k-group
  • reorder list
  • palindrome linked list
  • second half reversed
def reverse_list(head):
    prev = None
    curr = head
    while curr:
        next_node = curr.next    # 1. save the rest of the list
        curr.next = prev         # 2. point this node backwards
        prev = curr              # 3. move prev forward
        curr = next_node         # 4. move curr forward
    return prev                  # prev is the new head

Spot it when

  • Reverse a list or a group of k nodes.
  • Compare the first half with the second half.

Remember

  • Always save curr.next before you overwrite it.
  • When the loop ends, curr is None and prev is the old tail.

How problems bend it

  • Reorder or palindrome list: Find the middle with fast/slow pointers, reverse the second half, then walk both halves.
  • Reverse in groups of k: Check that k nodes exist, reverse them with this loop, and reconnect the group.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Linked List itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Follow k reachable nodesO(k)O(k)Finite acyclic valid-index chain; includes returned visit order. Aggregation alone can use constant auxiliary space.
Reverse or bypass copied linksO(m + k)O(m + k)m serialized nodes are copied and k reachable nodes may be scanned; local link assignment itself is constant time.

Space

O(k) for follow k reachable nodes; O(m) for reverse or bypass copied links.

Assumptions

  • Finite acyclic valid-index chain; includes returned visit order. Aggregation alone can use constant auxiliary space.
  • m serialized nodes are copied and k reachable nodes may be scanned; local link assignment itself is constant time.

Invariants Worth Saying Aloud

  1. Save the original successor before redirecting current's outgoing edge.
  2. previous is the reversed-prefix head; current is the first untouched node.
  3. Return the external head that reaches the resulting chain, and honor input ownership.

When To Use Or Avoid Linked List

Use It When

  • Work with existing node-based input when local relinking preserves node identity.
  • Use explicit cursors for constant-auxiliary-space pointer reversal.

Choose Another Tool When

  • Prefer a Python list when indexed reads dominate.
  • Use a deque for a routine FIFO queue rather than hand-maintained nodes.
  • Do not describe arbitrary deletion as constant time when its predecessor must first be found.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Reading the successor after overwriting it

Redirecting the outgoing edge destroys its original value. Reading afterward advances into the reversed prefix instead of the untouched suffix.

Prevent it: Save successor before modifying the current link.

Avoid

links[current] = previous
current = links[current]

Use instead

successor = links[current]
links[current] = previous
current = successor

Returning the former head after reversal

The old head becomes the tail. Its outgoing link is -1, so returning it loses access to the reversed prefix.

Prevent it: Return the completed reversed-prefix head stored in previous.

Avoid

result_head = old_head

Use instead

result_head = previous

Aliasing input links when a copy is promised

Assigning another name to the input list does not copy it. Relinking through that name also changes the caller's representation.

Prevent it: Copy the integer link array before edits when the Lab promises unchanged input.

Avoid

links = original
links[0] = -1

Use instead

links = original.copy()
links[0] = -1

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.