LeetCode 86: Partition List Solution
Master LeetCode problem 86 (Partition List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
86. Partition List
Problem Explanation
Explanation
To partition the linked list such that all nodes less than x come before nodes greater than or equal to x, we can maintain two separate linked lists - one for nodes less than x and the other for nodes greater than or equal to x. Then, we can merge these two lists at the end. We iterate through the original list and append nodes to their respective lists based on the comparison with x. Finally, we connect the tail of the "less than x" list to the head of the "greater than or equal to x" list.
- Time complexity: O(n) where n is the number of nodes in the linked list.
- Space complexity: O(1) as we are not using any extra space apart from a few pointers.
Solution Code
public ListNode partition(ListNode head, int x) {
ListNode lessThanX = new ListNode(0);
ListNode greaterThanOrEqualX = new ListNode(0);
ListNode lessThanXPtr = lessThanX;
ListNode greaterThanOrEqualXPtr = greaterThanOrEqualX;
while (head != null) {
if (head.val < x) {
lessThanXPtr.next = head;
lessThanXPtr = lessThanXPtr.next;
} else {
greaterThanOrEqualXPtr.next = head;
greaterThanOrEqualXPtr = greaterThanOrEqualXPtr.next;
}
head = head.next;
}
greaterThanOrEqualXPtr.next = null;
lessThanXPtr.next = greaterThanOrEqualX.next;
return lessThanX.next;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 86 (Partition List)?
This page provides optimized solutions for LeetCode problem 86 (Partition List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 86 (Partition List)?
The time complexity for LeetCode 86 (Partition List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 86 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 86 in Java, C++, or Python.