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 1:
Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2 Output: [1,2]
Constraints:
[0, 200]
.-100 <= Node.val <= 100
-200 <= x <= 200
To solve this cleanly, we use the two-pointer technique:
Create two dummy nodes:
ldummy
) for values less than x
gdummy
) for values greater than or equal to x
Traverse the original list:
< x
to the "less than" list.Connect the two lists together at the end.
Return the start of the combined list.
This method ensures we preserve the relative order of nodes while separating them based on the given value x
.
1/** 2 * Definition for singly-linked list. 3 * function ListNode(val, next) { 4 * this.val = (val===undefined ? 0 : val) 5 * this.next = (next===undefined ? null : next) 6 * } 7 */ 8 9/** 10 * @param {ListNode} head 11 * @param {number} x 12 * @return {ListNode} 13 */ 14var partition = function (head, x) { 15 let ldummy = new ListNode(0, null); // dummy head for < x 16 let gdummy = new ListNode(0, null); // dummy head for >= x 17 let ltrav = ldummy; 18 let gtrav = gdummy; 19 let trav = head; 20 21 while (trav) { 22 if (trav.val < x) { 23 ltrav.next = trav; 24 ltrav = ltrav.next; 25 } else { 26 gtrav.next = trav; 27 gtrav = gtrav.next; 28 } 29 trav = trav.next; 30 } 31 32 gtrav.next = null; // end of greater list 33 ltrav.next = gdummy.next; // connect two lists 34 return ldummy.next; // head of the final list 35};
Time Complexity: O(n)
We visit each node exactly once during traversal.
Space Complexity: O(1)
No extra space used except a few pointers (constant space), as we rearrange in-place.
1Input: head = [1,4,3,2,5,2], x = 3 2 3Step-by-step partition: 4< x list: [1 -> 2 -> 2] 5>= x list: [4 -> 3 -> 5] 6 7Final result: [1 -> 2 -> 2 -> 4 -> 3 -> 5]
This pattern of splitting and merging with dummy nodes is a great way to simplify many linked list problems. Once you get used to it, you’ll find similar applications in merging, sorting, and reordering linked lists.
Published by: Rakesh Reddy Peddamallu
Top Comments (0)