Leetcode #86: Partition List
In this guide, we solve Leetcode #86 Partition List in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Linked List, Two Pointers
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Python Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
l = ListNode()
r = ListNode()
tl, tr = l, r
while head:
if head.val < x:
tl.next = head
tl = tl.next
else:
tr.next = head
tr = tr.next
head = head.next
tr.next = None
tl.next = r.next
return l.next
Complexity
The time complexity is , where is the length of the original linked list. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.