Linked list coding interview questions

6 coding interview questions on linked lists, each with the correct answer and a full explanation.

Iterative reversal of a singly linked list. Which body is correct?
prev, cur = None, head
while cur:
    # body
return prev
Show answer

Answer

nxt = cur.next; cur.next = prev; prev = cur; cur = nxt
Save next before overwriting it, then link back and advance. Overwriting cur.next first makes cur = cur.next jump to prev and loses the rest. Setting prev before relinking makes cur point to itself. The last option also links cur to itself because prev was already moved.

Source: LeetCode 206. Reverse Linked List

Detect a cycle in O(1) space. Which is right?
Show answer

Answer

Fast moves two, slow moves one; a cycle exists if they meet
Floyd's tortoise and hare meets inside any cycle and uses O(1) space. Mutating values corrupts input and fails if None is a valid value. A step cap is a guess tied to constraints. A visited set is correct but O(n) space.

Source: LeetCode 141. Linked List Cycle

Remove the nth node from the end in one pass, where n can equal the list length. What avoids a special case for removing the head?
Show answer

Answer

A dummy node before head, with both pointers starting at it
With a dummy, the slow pointer lands on the node before the target even when the target is the head. Starting at head needs a separate branch for n equal to length. Reversing is extra passes and still has edge cases. Length then walk is two passes, not one.

Source: LeetCode 19. Remove Nth Node From End of List

Merge two sorted lists of lengths m and n. What is the time and extra space of the iterative merge?
Show answer

Answer

O(m + n) time, O(1) extra space
Relinking existing nodes behind a dummy needs only pointers. Extra O(m + n) space is the recursive version's stack or copying into new nodes. O(m n) is inserting each node by scanning. Sorting the union adds an unnecessary log factor.

Source: LeetCode 21. Merge Two Sorted Lists

Middle of the Linked List: return the second middle when length is even. Loop: while fast and fast.next: slow, fast = slow.next, fast.next.next. Both start at head. What does it return for 1->2->3->4?
Show answer

Answer

Node 3
For 4 nodes, slow moves twice to node 3, which is the second middle. Node 2 is what you get if fast starts at head.next. Node 4 is the tail. The guard checks fast.next before reading fast.next.next, so nothing raises.

Source: LeetCode 876. Middle of the Linked List

Reorder List L0, Ln, L1, Ln-1 in place with O(1) extra space. Approach?
Show answer

Answer

Find the middle with slow and fast, reverse the second half, then merge the two halves alternately. Cut the first half at the middle to avoid a cycle. O(n) time, O(1) space.

Source: LeetCode 143. Reorder List

These questions come from the Coding Interview Practice pack in Bertopia.

More coding topics

Practise these on your commute