LeetCode 86: Partition List is a Medium linked list problem. This Python walkthrough develops a stable dual lists solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Linked List |
| Reusable pattern | stable dual lists |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.
For this problem specifically, append nodes to separate less-than and greater-or-equal chains, then connect the chains and terminate the second tail. The invariant worth writing beside the code is: Each chain preserves the original relative order of its processed nodes.
Step-by-step algorithm
- Identify the input state consumed by
partition(head, x)and initialize the data required by the stable dual lists pattern. - Append nodes to separate less-than and greater-or-equal chains, then connect the chains and terminate the second tail.
- After each update, verify the page’s central invariant: Each chain preserves the original relative order of its processed nodes.
- Finish only after the boundary behavior is covered: One partition may remain empty; terminate the reused tail to avoid a cycle.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def partition(self, head, x):
low_dummy = low = ListNode()
high_dummy = high = ListNode()
while head:
following = head.next
if head.val < x:
low.next = head; low = low.next
else:
high.next = head; high = high.next
head = following
high.next = None
low.next = high_dummy.next
return low_dummy.nextReading the implementation
The main entry point is partition(head, x). The named working state includes low_dummy, high_dummy, following, head; those variables make the stable dual lists state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, append nodes to separate less-than and greater-or-equal chains, then connect the chains and terminate the second tail.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Append nodes to separate less-than and greater-or-equal chains, then connect the chains and terminate the second tail. Each update records the current item without invalidating earlier decisions; consequently, each chain preserves the original relative order of its processed nodes.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert listed(Solution().partition(linked([1,4,3,2,5,2]),3)) == [1,2,2,4,3,5]Common mistakes and edge cases
- Problem-specific boundary: One partition may remain empty; terminate the reused tail to avoid a cycle.
- Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
- Invariant check: after every update, confirm that each chain preserves the original relative order of its processed nodes.
Interview review checklist
- Explain why stable dual lists matches the structure of this input.
- State the invariant in one sentence before tracing code: Each chain preserves the original relative order of its processed nodes.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: One partition may remain empty; terminate the reused tail to avoid a cycle.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 61. Rotate List · Next: 146. LRU Cache