Imagine you have a queue of people waiting, and you want to rearrange them so that everyone shorter than a certain height stands in front, preserving their relative order.
Given the head of a singly linked list and a value x, partition the list so that all nodes less than x come before nodes greater than or equal to x. The original relative order of the nodes in each partition should be preserved. Return the head of the modified list.
1 ≤ n ≤ 10^5 (number of nodes in the list)-10^6 ≤ Node.val, x ≤ 10^6
Edge cases: All nodes less than x → list remains unchangedAll nodes greater or equal to x → list remains unchangedList with only one node → output is the same node
def partition(head: Optional[ListNode], x: int) -> Optional[ListNode]:public ListNode partition(ListNode head, int x)ListNode* partition(ListNode* head, int x)function partition(head, x)
def partition(head, x):
# Write your solution here
pass
class Solution {
public ListNode partition(ListNode head, int x) {
// Write your solution here
return null;
}
}
#include <vector>
using namespace std;
ListNode* partition(ListNode* head, int x) {
// Write your solution here
return nullptr;
}
function partition(head, x) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [4,3,5,1,2,2]Incorrectly placing nodes greater or equal to x before nodes less than x, violating partition order.✅ Use two dummy heads to build separate lists for nodes < x and nodes >= x, then concatenate less list before greater or equal list.
Wrong: [1,4,3,2,5,2]Returning original list without partitioning or failing to reorder nodes.✅ Implement partition logic that separates nodes based on value and preserves relative order.
Wrong: [5]Crashing or returning incorrect output on single node input due to null pointer or edge case mishandling.✅ Check for null or single node input and return head as is without modification.
Wrong: [3,3,3]Incorrectly moving nodes equal to x into less than partition or losing order.✅ Ensure nodes with val >= x are appended to the second list without reordering.
Wrong: Timeout or no outputUsing nested loops or multiple passes causing O(n^2) complexity.✅ Use a single pass with two dummy heads to achieve O(n) time complexity.