AlgoInsight

DSA problem

Partition List

MediumLinked ListPattern: Linked Listtop300AmazonMicrosoftBloombergAdobeApple

Given the head of a linked list and a value x, partition the list so that all nodes with a value strictly less than x come before all nodes with a value greater than or equal to x. The crucial requirement is that you must preserve the original relative order of the nodes within each of the two partitions.

This is essentially the partition step of a stable sort applied to a linked list. Because the ordering within each group must be maintained, you cannot simply swap nodes around arbitrarily; a value-comparison-based bubbling would also be unstable and slow.

Rather than mutating values in place, the cleanest technique splits the original list into two independent sublists during a single traversal. One sublist collects every node whose value is less than x, and the other collects every node whose value is greater than or equal to x.

The intuition is to maintain two dummy-headed lists, a less list and a greater list. As we scan the original list once, we append each node to the tail of the appropriate list. At the end, we concatenate the less list with the greater list and crucially terminate the greater list's tail with null to avoid a cycle. This gives a stable partition in O(n) time and O(1) extra space.

Examples

Example 1
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Explanation: Nodes with value less than 3 are 1, 2, 2 (in original order). Nodes with value at least 3 are 4, 3, 5 (in original order). Concatenating gives [1,2,2,4,3,5].
Example 2
Input: head = [2,1], x = 2
Output: [1,2]
Explanation: Node 1 is less than 2 and node 2 is at least 2, so the less list is [1] and the greater list is [2], yielding [1,2].
Example 3
Input: head = [], x = 0
Output: []
Explanation: An empty list has no nodes to partition, so the result is an empty list.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersin-placestable-partition

Browse all DSA problems