Partition List (LeetCode 86): Solution and Explanation

Medium
Linked List
Two Pointers

Given the head of a linked list and a value x, rearrange the nodes so all values below x come first, followed by all values of x or more, with each group keeping its original order.

Intuition

The requirement to keep the original order inside each group rules out swapping tricks like the partition step of quicksort, which scramble order. What does keep order is reading the list from left to right and writing each node out in the order you meet it.

So deal the nodes like cards into two piles. Every node below x goes on the end of the first pile, everything else on the end of the second. Since you only ever append, each pile is automatically in original order.

Linked lists make this cheap: moving a node to a pile is just a pointer assignment, no copying. Two dummy heads remove the special case of an empty pile, and two tail pointers make each append O(1).

At the end, glue the piles together. One detail matters: the last node of the second pile still has its old next, which may point back into the first pile. Setting it to null before joining prevents a cycle.

Approach: Two dummy lists with tail pointers

  1. Create two dummy nodes, before and after, and tail pointers b = before, a = after.
  2. Walk the list with curr. If curr.val < x, set b.next = curr and move b forward; otherwise set a.next = curr and move a forward.
  3. Move curr = curr.next and repeat until curr is null.
  4. Set a.next = None to cut the stale pointer left on the last big node.
  5. Set b.next = after.next to join the lists, and return before.next.

Step-by-step example

head = [1,4,3,2,5,2], x = 3
  1. 1 < 3, so it goes to the before lane: before -> 1.
  2. 4 and 3 are at least 3, so they go to the after lane in that order: after -> 4 -> 3.
  3. 2 joins before (before -> 1 -> 2), 5 joins after (after -> 4 -> 3 -> 5), and the last 2 joins before (before -> 1 -> 2 -> 2).
  4. The walk ends. Node 5 still points at the last 2 from the original list, so a.next = None cuts that link.
  5. b.next = after.next links the last 2 to 4, giving 1 -> 2 -> 2 -> 4 -> 3 -> 5.

Code: Python, Java, C++

1class Solution:
2    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
3        before = ListNode(0)
4        after = ListNode(0)
5        b, a = before, after
6        curr = head
7        while curr:
8            if curr.val < x:
9                b.next = curr
10                b = b.next
11            else:
12                a.next = curr
13                a = a.next
14            curr = curr.next
15        a.next = None
16        b.next = after.next
17        return before.next
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is visited once and moved with a constant number of pointer assignments.

Space

O(1)

The nodes are relinked in place; only two dummy nodes and a few pointers are added.

Other approaches

Copy values into two arrays (time O(n), space O(n))

Collect values below x and the rest into two arrays, then write them back into the nodes or build a new list. Simple, but it uses O(n) extra memory and does not move the nodes themselves.

Move small nodes forward in place (time O(n), space O(1))

Keep a pointer to the end of the small region at the front and splice each small node found later to just after it. It works with one list but needs careful bookkeeping of the predecessor of each moved node.

Common mistakes

  • Forgetting a.next = None. The last node of the after lane may still point into the before lane, and joining then creates a cycle.
  • Using <= instead of <. Nodes equal to x belong to the second group.
  • Swapping values in place like quicksort partition, which breaks the required relative order.
  • Returning head instead of before.next. The original head may now be in the second group.

Frequently asked questions

Why are two dummy nodes used?

Either group can be empty. With a dummy at the front of each, appending and joining work the same way whether a group has zero or many nodes, so there are no special cases.

Why is the order inside each group preserved?

Nodes are visited from head to tail and always appended to the end of their group, so they come out in the same order they went in.

What goes wrong without setting a.next to None?

The last node of the after group keeps its original next. If that points to a node in the before group, the final list loops back on itself and never ends.

Is this the same as the quicksort partition?

It splits around a pivot like quicksort, but it is stable: relative order inside each side is kept, which the classic in-place array partition does not guarantee.