Partition List

Move every node below x to the front of a linked list, keeping the order inside both groups.

Given the head of a linked list and a value x, rearrange the nodes so that every node with a value less than x comes before every node with a value of x or more. Inside each of these two groups, the nodes must keep the order they had in the original list.

Example 1
Input: head = [1, 4, 3, 2, 5, 2], x = 3
Output: [1, 2, 2, 4, 3, 5]
Example 2
Input: head = [2, 1], x = 2
Output: [1, 2]
Solution

The Idea

Picture a row of numbered cards that you sort into two new rows: cards below 3 in the first row, all other cards in the second. Each card goes at the right end of its row, so each row keeps the cards in the order you met them. Put the first row in front of the second and you have the answer.

Here the cards are the nodes of a linked list. In a linked list, the cards become nodes, and each node points to the one after it through a link called next. At the end of the row that link is null, meaning there is no next node. The list is handed over as its first node, head.

Walk through Example 1 with x = 3. The values below 3 are 1, 2 and 2, in that order. The values of 3 or more are 4, 3 and 5. Put together, that is [1, 2, 2, 4, 3, 5]. Notice that 4, 3, 5 is not sorted: the problem only asks for two groups, each in its original order. In Example 2, the 2 is equal to x, so it belongs to the second group and ends up after the 1.

With an array, we could copy the values into two new arrays and write them back. A linked list allows something cheaper. A node's place in the list is decided only by which next pointer leads to it. So can we move the nodes into two groups just by changing pointers, without copying a single value?

We can. Walk the list once, and hook each node onto the end of one of two chains: a small chain for values less than x, and a big chain for values of x or more. At the end, join the small chain to the big chain. Look at the picture below.

The list 1, 4, 3, 2, 5, 2 with x = 3 is split into two chains, each starting at a dummy node. The small chain, less than 3, holds 1, 2, 2. The big chain, 3 or more, holds 4, 3, 5 and ends in null. The last node of the small chain is joined to 4.

The top row is the list, with each node coloured by the chain it goes to. The row labelled "small chain" holds 1, 2, 2, and the row labelled "big chain" holds 4, 3, 5, each in the order the walk met them. Each chain begins at a dashed box labelled "dummy", a spare node with no real value that only marks where the chain begins. The orange arrow labelled "join the chains" links the last 2 to the 4. The orange arrow after 5 points to null, so the list ends there.

Solution Approach

Turning that idea into code means settling three things: where each chain starts, how a node is added to the end of a chain, and how the chains are ended and joined. Copying the values is the simple alternative, and it costs more memory.

Where each chain starts

What does a chain look like before its first node arrives? It is empty, and adding the first node to an empty chain would need its own special case. A dummy node avoids that. It is a spare node, created before the walk, that holds no real value and only sits in front of the chain.

The code makes two of them, smallHead and bigHead. Every real node, including the first, is then added after some existing node. When the walk is done, the real small chain starts at smallHead.next, and the real big chain at bigHead.next.

Adding a node to the end of a chain

How do we reach the end of a chain without walking along it each time? Keep a pointer to its last node: small for the small chain and big for the big chain, both starting on their dummy. Adding a node to the small chain is then two assignments: small.next = node links it on, and small = node makes it the new last node.

The walk meets the nodes in their original order and always adds at the end, so each chain keeps that order, as the problem asks. The test is node.val < x, so a node equal to x goes to the big chain, like the 2 in Example 2.

Ending and joining the chains

Where does the last node of each chain point when the walk ends? Still to its old next from the original list. For the small chain that does not matter, because the join overwrites it: small.next = bigHead.next links the last small node to the first big node.

The big chain's last node is different. In Example 1 it is the 5, and its next still points to the final 2, which is now in the small chain. Left alone, the result would run 2, 4, 3, 5, 2, 4, 3, 5 and never end. So the code sets big.next = null before joining, which is the orange arrow from 5 to null in the picture.

These two lines also handle a chain that stays empty. With no big nodes, bigHead.next is null, so the join just ends the small chain. With no small nodes, small is still on smallHead, so the join makes smallHead.next point at the big chain.

Copying the values instead

Would copying be simpler? You could collect the small values and the big values into two lists, then write them back into the nodes in that order. That also takes one pass, but it stores a copy of every value. Relinking the nodes needs only the two dummy nodes, however long the list is.

Java Solution

The method partition works in these steps:

  1. First, create the two dummy nodes, smallHead and bigHead, and the two last-node pointers, small and big, which start on those dummies.
  2. Walk the list with a for loop, moving node from head until it is null. If node.val is less than x, add the node to the small chain with small.next = node and small = node. Otherwise, add it to the big chain the same way, with big.
  3. After the loop, end the big chain with big.next = null.
  4. Join the chains with small.next = bigHead.next.
  5. Return smallHead.next, the first real node of the joined list.

The main method builds each list with a small helper, build, and prints the result with show. It runs both examples, a list whose big nodes are in descending order, a list with every value below x, one with no value below x, and an empty list.

Java
public class PartitionList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static ListNode partition(ListNode head, int x) {
        ListNode smallHead = new ListNode(0);  // dummy in front of the "less than x" chain
        ListNode bigHead = new ListNode(0);    // dummy in front of the "x or more" chain
        ListNode small = smallHead;            // last node of the small chain so far
        ListNode big = bigHead;                // last node of the big chain so far
        for (ListNode node = head; node != null; node = node.next) {
            if (node.val < x) {
                small.next = node;             // append to the small chain
                small = node;
            } else {
                big.next = node;               // append to the big chain
                big = node;
            }
        }
        big.next = null;                       // end the big chain: it may still point back
        small.next = bigHead.next;             // small chain, then big chain
        return smallHead.next;
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode n = head; n != null; n = n.next) {
            sb.append(n.val).append(n.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(partition(build(1, 4, 3, 2, 5, 2), 3)));
        System.out.println(show(partition(build(2, 1), 2)));
        System.out.println(show(partition(build(5, 1, 4, 2, 3), 3)));
        System.out.println(show(partition(build(1, 2, 3), 10)));
        System.out.println(show(partition(build(7, 8, 9), 1)));
        System.out.println(show(partition(build(), 5)));
    }
}

Running it prints:

Output
[1, 2, 2, 4, 3, 5]
[1, 2]
[1, 2, 5, 4, 3]
[1, 2, 3]
[7, 8, 9]
[]

The first line matches Example 1, with 4, 3, 5 kept in their original order, and the second line, [1, 2], shows the 2 that equals x moved behind the 1. Look at the third line: from [5, 1, 4, 2, 3] with x = 3, the 1 and 2 move to the front, and 5, 4, 3 stay as they came, even though they are not sorted.

The next two lines each leave one chain empty. With x = 10, all of 1, 2, 3 go to the small chain and the join adds null. With x = 1, all of 7, 8, 9 go to the big chain, and the result is [7, 8, 9] unchanged. The last line, [], comes from the empty list: the loop never runs and smallHead.next is null.

The line big.next = null is short but needed. A copy of the method without that line, run on Example 1 and stopped after 15 nodes, gives 1 2 2 4 3 5 2 4 3 5 2 4 3 5 2. After the 5 comes the final 2 again, its old next, and the list goes round forever.

Complexity

The method walks the list once and does a fixed amount of work at each node.

  • Time: O(n) for a list of n nodes: the for loop visits each node once, and adding it to a chain takes two pointer assignments, because small and big already sit at the chain ends.
  • Space: O(1). Only the two dummy nodes and a few pointers are new. The existing nodes are relinked, not copied.

Splitting a list by position instead of by value is Odd Even Linked List.