86. Partition List 🔗
Difficulty: Medium - Tags: Linked List
Problem Statement 📜
Given the head of a linked list and a value x, partition it such that:
All nodes with values less than
xcome before nodes with values greater than or equal tox.The relative order of the nodes in each partition should be preserved.
Examples 🌟
🔹 Example 1:

Input:
Output:
🔹 Example 2:
Input:
Output:
Constraints ⚙️
The number of nodes in the list is in the range
[0, 200].-100 <= Node.val <= 100.-200 <= x <= 200.
Solution 💡
To partition the list:
Use two pointers (
lessandgreater) to track nodes:lesscollects nodes with values less thanx.greatercollects nodes with values greater than or equal tox.
Reconnect the two partitions at the end.
Java Solution
Explanation of the Solution
Dummy Nodes:
Use dummy nodes to simplify handling the head of each partition.
Partitioning:
Traverse the original list, adding nodes with values
< xto thelesspartition and others to thegreaterpartition.
Reconnecting:
End the
greaterpartition to prevent cycles.Connect the
lesspartition to the start of thegreaterpartition.
Time Complexity ⏳
O(n): Each node is visited once.
Space Complexity 💾
O(1): Uses constant extra space.
Follow-up 🧐
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.
Last updated
Was this helpful?