86. Partition List LeetCode Solution
In this guide, you will get 86. Partition List LeetCode Solution with the best time and space complexity. The solution to Partition List problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Partition List solution in C++
- Partition List solution in Java
- Partition List solution in Python
- Additional Resources
Problem Statement of Partition List
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:
The number of nodes in the list is in the range [0, 200].
-100 <= Node.val <= 100
-200 <= x <= 200
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
86. Partition List LeetCode Solution in C++
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode beforeHead(0);
ListNode afterHead(0);
ListNode* before = &beforeHead;
ListNode* after = &afterHead;
for (; head; head = head->next)
if (head->val < x) {
before->next = head;
before = head;
} else {
after->next = head;
after = head;
}
after->next = nullptr;
before->next = afterHead.next;
return beforeHead.next;
};
};
/* code provided by PROGIEZ */
86. Partition List LeetCode Solution in Java
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode beforeHead = new ListNode(0);
ListNode afterHead = new ListNode(0);
ListNode before = beforeHead;
ListNode after = afterHead;
for (; head != null; head = head.next)
if (head.val < x) {
before.next = head;
before = head;
} else {
after.next = head;
after = head;
}
after.next = null;
before.next = afterHead.next;
return beforeHead.next;
}
}
// code provided by PROGIEZ
86. Partition List LeetCode Solution in Python
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
beforeHead = ListNode(0)
afterHead = ListNode(0)
before = beforeHead
after = afterHead
while head:
if head.val < x:
before.next = head
before = head
else:
after.next = head
after = head
head = head.next
after.next = None
before.next = afterHead.next
return beforeHead.next
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.