Partition List
Difficulty: Medium · Pattern: Linked List · LeetCode #86
Rearrange the list so all nodes with values less than x come before nodes with values ≥ x, preserving the original relative order within each part.
Examples
text
1 → 4 → 3 → 2 → 5 → 2, x = 3 → 1 → 2 → 2 → 4 → 3 → 5
2 → 1, x = 2 → 1 → 2Hints
- Build two separate lists as you scan, then concatenate.
Approach
Keep two dummies, before and after. Append each node to the appropriate tail. Finally terminate the after list (afterTail.next = null, to avoid cycles) and link beforeTail.next = after.next. Stable, O(n), O(1).
Complexity
Time: O(n). Space: O(1).
Python solution
def partition(head, x):
before = bt = ListNode()
after = at = ListNode()
while head:
if head.val < x:
bt.next = head; bt = head
else:
at.next = head; at = head
head = head.next
at.next = None
bt.next = after.next
return before.nextJavaScript solution
function partition(head, x) {
const before = new ListNode(), after = new ListNode(); let bt = before, at = after;
for (; head; head = head.next) { if (head.val < x) { bt.next = head; bt = head; } else { at.next = head; at = head; } }
at.next = null; bt.next = after.next; return before.next;
}