86. Partition List ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
Given the head of a linked list and a value x
, partition it such that:
All nodes with values less than x
come before nodes with values greater than or equal to x
.
The relative order of the nodes in each partition should be preserved.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
The number of nodes in the list is in the range [0, 200]
.
-100 <= Node.val <= 100
.
-200 <= x <= 200
.
To partition the list:
Use two pointers (less
and greater
) to track nodes:
less
collects nodes with values less than x
.
greater
collects nodes with values greater than or equal to x
.
Reconnect the two partitions at the end.
Dummy Nodes:
Use dummy nodes to simplify handling the head of each partition.
Partitioning:
Traverse the original list, adding nodes with values < x
to the less
partition and others to the greater
partition.
Reconnecting:
End the greater
partition to prevent cycles.
Connect the less
partition to the start of the greater
partition.
O(n): Each node is visited once.
O(1): Uses constant extra space.
This solution maintains the relative order of nodes in both partitions while achieving optimal time and space complexity. It is robust against edge cases like empty lists or when all nodes belong to one partition.
You can find the full solution here.