← Back to Leo Academy Masterclass

Problem #86: Partition List

Medium Linked List

Intuition & Strategy Breakdown

Maintain two separate linked lists (less and greater_equal) using dummy nodes. Iterate through original list, partitioning nodes into corresponding lists, then connect them.

Python Solution

class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        before_head = ListNode(0)
        before = before_head
        after_head = ListNode(0)
        after = after_head
        
        curr = head
        while curr:
            if curr.val < x:
                before.next = curr
                before = before.next
            else:
                after.next = curr
                after = after.next
            curr = curr.next
        
        after.next = None
        before.next = after_head.next
        
        return before_head.next

Java Solution

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(0);
        ListNode before = beforeHead;
        ListNode afterHead = new ListNode(0);
        ListNode after = afterHead;

        while (head != null) {
            if (head.val < x) {
                before.next = head;
                before = before.next;
            } else {
                after.next = head;
                after = after.next;
            }
            head = head.next;
        }

        after.next = null;
        before.next = afterHead.next;

        return beforeHead.next;
    }
}
Watch Interactive Video on Leo Academy Main App