Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
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 <= 200Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List · Two Pointers
[1,4,3,2,5,2] 3
[2,1] 2
partition-array-according-to-given-pivot)/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode lessDummy = new ListNode(0), greaterDummy = new ListNode(0);
ListNode less = lessDummy, greater = greaterDummy;
while (head != null) {
if (head.val < x) {
less.next = head;
less = less.next;
} else {
greater.next = head;
greater = greater.next;
}
head = head.next;
}
greater.next = null;
less.next = greaterDummy.next;
return lessDummy.next;
}
}
/**
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func partition(head *ListNode, x int) *ListNode {
lessDummy := &ListNode{}
greaterDummy := &ListNode{}
less, greater := lessDummy, greaterDummy
for head != nil {
if head.Val < x {
less.Next = head
less = less.Next
} else {
greater.Next = head
greater = greater.Next
}
head = head.Next
}
greater.Next = nil
less.Next = greaterDummy.Next
return lessDummy.Next
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
less_dummy = ListNode(0)
greater_dummy = ListNode(0)
less, greater = less_dummy, greater_dummy
while head:
if head.val < x:
less.next = head
less = less.next
else:
greater.next = head
greater = greater.next
head = head.next
greater.next = None
less.next = greater_dummy.next
return less_dummy.next
/**
* Definition for singly-linked list.
* #[derive(PartialEq, Eq, Clone, Debug)]
* pub struct ListNode {
* pub val: i32,
* pub next: Option<Box<ListNode>>
* }
* impl ListNode {
* #[inline]
* fn new(val: i32) -> Self {
* ListNode { next: None, val }
* }
* }
*/
impl Solution {
pub fn partition(head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {
let mut vals = Vec::new();
let mut cur = head;
while let Some(mut node) = cur {
vals.push(node.val);
cur = node.next.take();
}
let mut out_vals = Vec::new();
for &v in &vals {
if v < x {
out_vals.push(v);
}
}
for &v in &vals {
if v >= x {
out_vals.push(v);
}
}
let mut out: Option<Box<ListNode>> = None;
for &v in out_vals.iter().rev() {
out = Some(Box::new(ListNode { val: v, next: out }));
}
out
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function partition(head: ListNode | null, x: number): ListNode | null {
const lessDummy = new ListNode(0);
const greaterDummy = new ListNode(0);
let less = lessDummy;
let greater = greaterDummy;
while (head) {
if (head.val < x) {
less.next = head;
less = less.next;
} else {
greater.next = head;
greater = greater.next;
}
head = head.next;
}
greater.next = null;
less.next = greaterDummy.next;
return lessDummy.next;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.