Partition List (LeetCode 86): Solution and Explanation
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
- Create two dummy nodes,
beforeandafter, and tail pointersb = before,a = after. - Walk the list with
curr. Ifcurr.val < x, setb.next = currand movebforward; otherwise seta.next = currand moveaforward. - Move
curr = curr.nextand repeat untilcurris null. - Set
a.next = Noneto cut the stale pointer left on the last big node. - Set
b.next = after.nextto join the lists, and returnbefore.next.
Step-by-step example
head = [1,4,3,2,5,2], x = 3
- 1 < 3, so it goes to the before lane: before -> 1.
- 4 and 3 are at least 3, so they go to the after lane in that order: after -> 4 -> 3.
- 2 joins before (before -> 1 -> 2), 5 joins after (after -> 4 -> 3 -> 5), and the last 2 joins before (before -> 1 -> 2 -> 2).
- The walk ends. Node 5 still points at the last 2 from the original list, so
a.next = Nonecuts that link. b.next = after.nextlinks 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.next1class Solution {
2 public ListNode partition(ListNode head, int x) {
3 ListNode before = new ListNode(0);
4 ListNode after = new ListNode(0);
5 ListNode b = before, a = after;
6 ListNode curr = head;
7 while (curr != null) {
8 if (curr.val < x) {
9 b.next = curr;
10 b = b.next;
11 } else {
12 a.next = curr;
13 a = a.next;
14 }
15 curr = curr.next;
16 }
17 a.next = null;
18 b.next = after.next;
19 return before.next;
20 }
21}1class Solution {
2public:
3 ListNode* partition(ListNode* head, int x) {
4 ListNode before(0), after(0);
5 ListNode* b = &before;
6 ListNode* a = &after;
7 ListNode* curr = head;
8 while (curr) {
9 if (curr->val < x) {
10 b->next = curr;
11 b = b->next;
12 } else {
13 a->next = curr;
14 a = a->next;
15 }
16 curr = curr->next;
17 }
18 a->next = nullptr;
19 b->next = after.next;
20 return before.next;
21 }
22};Time and space complexity
O(n)
Each node is visited once and moved with a constant number of pointer assignments.
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
headinstead ofbefore.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.