SDE & MLE Prep

86. Partition List

Problem

Rearrange a linked list so every node with value less than x comes before every node with value ≥ x, keeping the original relative order within both groups.

Example: 1→4→3→2→5→2, x = 3 → 1→2→2→4→3→5

Build two chains (< x and ≥ x) with dummy heads, preserving order, then join them. Terminate the second chain!

Complexity: O(n).

class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        small = s = ListNode()
        big = b = ListNode()
        while head:
            if head.val < x:
                s.next = s = head
            else:
                b.next = b = head
            head = head.next
        b.next = None
        s.next = big.next
        return small.next