Linked lists
A linked list gives up index access to get O(1) insert and delete at a known node; interview problems are pointer surgery with three tools: a dummy head, in-place reversal and fast/slow pointers.
Analogy: A treasure hunt: each clue only says where the next one is. Reaching clue 10 means following nine clues, but adding one means rewriting a single note.
How it works
- A node holds a value and a
nextpointer: O(n) access, O(1) insert or delete after it. - A dummy head removes the special case for the first node; return
dummy.next. - Reverse in place: save
next, point the node back atprev, advance. O(1) space. - Fast/slow:
slowis at the middle whenfastreaches the end; they meet inside a cycle. - Hard problems compose them: find the middle, reverse the second half, then merge or compare.
Check yourself
Answer to mark it learned; your answers aren't scored.
Check whether a singly linked list of n nodes is a palindrome using O(1) extra space. Which plan works?
Go deeper
Solve it in Python 10
- Node at the halfway pointeasy
- Linked list, back to fronteasy
- Splice two sorted listseasy
- Add numbers stored as digit listsmedium
- Clone a list with jump linksmedium
- First node of the cyclemedium
- Interleave the two ends of a listmedium
- List that reads the same backwardsmedium
- Unlink the k-th node from the backmedium
- Flip a list in blocks of khard
Full explanation
A linked list is a chain of nodes; each holds a value and a next pointer (plus prev if doubly linked). Reaching the k-th node costs O(k), but inserting or deleting right after a node you already hold is O(1): you rewire pointers and nothing shifts. Removing the node itself needs its predecessor, or a prev pointer.
Interview problems are pointer surgery with three tools:
- Dummy head: a placeholder node before the real head, so inserting or deleting the first node is not a special case. Return
dummy.next. - In-place reversal: walk the list; save
next, point the current node back atprev, advance. O(n) time, O(1) space. - Fast/slow pointers:
fastmoves two steps,slowone.slowis at the middle whenfastreaches the end, and they meet if there is a cycle (Floyd, in Two pointers).
Merging two sorted lists uses a dummy head and a tail that always takes the smaller front node.
Harder problems compose them: a palindrome check is middle + reverse + compare. Draw the pointers before you code.
Code Reverse, find the middle, merge two sorted lists
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def reverse(head):
prev, curr = None, head
while curr:
nxt = curr.next # save it before overwriting the link
curr.next = prev # point this node backward
prev, curr = curr, nxt
return prev # the old tail is the new head
def middle(head):
slow = fast = head
while fast and fast.next: # fast moves 2 steps, slow moves 1
slow, fast = slow.next, fast.next.next
return slow # the second middle if the length is even
def merge(a, b):
dummy = tail = ListNode() # dummy head: the first node is not a special case
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 whatever is left
return dummy.nextReal example
Reorder list 1→2→3→4→5 into 1→5→2→4→3 with O(1) extra space. Three routines: (1) fast/slow finds the middle, node 3; cut after it: 1→2→3 and 4→5. (2) Reverse the second half: 5→4. (3) Weave them, alternating nodes: 1→5→2→4→3. Three O(n) passes, no extra memory. Copying the nodes into an array is simpler but costs O(n) space, and the interviewer will ask you to remove it.
Trade-offs +3 · −3
+ You gain
- O(1) insert and delete at a node you hold; nothing shifts.
- Three routines solve most problems in O(n) time and O(1) extra space.
- Building block of LRU caches, queues and hash-map buckets.
− You pay
- No random access: reaching index k costs O(k), so no binary search.
- One pointer per node and scattered memory: slower than arrays in practice.
- Pointer bugs are silent: one wrong assignment loses the rest of the list or creates a cycle.
Use it when
The input is a linked list, or you need O(1) splice, move-to-front or removal at a node you hold (LRU cache, queues). Aim for in-place, O(1) space.
Avoid it when
You need index access or binary search. In production, default to a dynamic array or collections.deque; hand-rolled nodes are rarely the fastest choice.
Numbers to know 4
- Access and search O(n); insert or delete O(1) once you hold the previous node (any node, if doubly linked).
- Reverse, find the middle, detect a cycle: O(n) time, O(1) space.
- Merge two sorted lists of n and m nodes: O(n + m) time, O(1) extra space.
- Python:
list.pop(0)andinsert(0, v)are O(n);collections.dequedoes both ends in ~O(1).
Common pitfalls 4
- Overwriting
curr.nextbefore saving it: the rest of the list is gone. - Writing
while fast.nextwithout checkingfastfirst: it crashes on an empty or even-length list. - Returning
headwhen the head may have changed; use a dummy and returndummy.next. - Splitting a list without setting the first half's last
nexttoNone: you leave a cycle.
Interview questions 3
Answer out loud first, then reveal.
How do you approach a linked-list problem?Show answer
First I ask: singly or doubly linked, may I modify it in place, can it contain a cycle? Then I draw three or four nodes and map the problem to the routines: a dummy head if the head can change, reversal, fast/slow for the middle or a cycle. Most problems are a composition, like palindrome = middle + reverse + compare. I finish by testing empty, one-node and two-node lists, where pointer bugs show up.
Reverse only the nodes between positions left and right, in one pass.Show answer
A dummy head covers left = 1. I walk to the node just before left, reverse the next right − left + 1 nodes with the usual prev/curr loop, and reconnect two links: the node before the segment points to the segment's new head, and the segment's old first node, now its tail, points to the node after it. O(n) time, O(1) space. Reversing in groups of k repeats this step.
When would you use a linked list in production?Show answer
Rarely as a plain sequence: arrays win on memory locality. I use one when I need O(1) removal or reordering of an element I already hold. An LRU cache pairs a hash map with a doubly linked list, and the Linux kernel embeds circular doubly linked lists in its structs. In Python I'd reach for collections.deque or OrderedDict before writing nodes by hand.