Partition List — LeetCode 86 Python Solution
- Problem
- #86
- Pattern
- Linked List
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
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.nextComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the original linked list |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 86. Partition List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 86. Partition List?
- LeetCode 86. Partition List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 86. Partition List?
- The Python solution on this page runs in O(n), where n is the length of the original linked list.
- What is the space complexity of LeetCode 86. Partition List?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 86. Partition List cover?
- LeetCode 86. Partition List is tagged Linked List and Two Pointers on LeetCode.