InterviewPrepKit

Home / Coding / Linked List

Partition List

medium Original β†—
Solving tips
  • Recognize this as a stable regrouping: don't swap nodes in place (that breaks stability), instead deal each node into two separate chains in one pass.
  • Use two dummy-headed chains, a 'less than x' chain and a 'greater-or-equal' chain, then splice the less tail onto the geq chain's first real node.
  • The classic bug: forgetting to null-terminate the geq chain (geq.next = None) before splicing creates a cycle.
  • Target O(n) time and O(1) extra space; appending to a tail preserves original order for free.

Problem

Given the head of a singly linked list and an integer x, rearrange the list so that every node with value less than x appears before every node with value greater than or equal to x.

The partition must be stable: within each of the two groups, nodes keep their original relative order.

Examples

  • Input: head = [1, 4, 3, 2, 5, 2], x = 3 β†’ Output: [1, 2, 2, 4, 3, 5] Values < 3 are 1, 2, 2 (original order kept); values >= 3 are 4, 3, 5 (original order kept).
  • Input: head = [2, 1], x = 2 β†’ Output: [1, 2] 1 < 2 moves ahead of 2, which is >= 2.
  • Input: head = [5, 6, 7], x = 3 β†’ Output: [5, 6, 7] No value is below 3, so nothing moves.

Constraints

  • 0 <= n <= 200 where n is the number of nodes.
  • -100 <= Node.val <= 100, -200 <= x <= 200.

The list is tiny, so almost anything passes β€” the point of the exercise is the O(n) time / O(1) extra-space pointer solution and getting stability right.

Think about it first

Hint 1 Quicksort-style in-place swapping breaks the required stability. What data-structure-free way is there to keep two groups in original order?
Hint 2 Imagine dealing the nodes, one pass, into two separate lists: a "less than x" list and a "greater or equal" list. Appending to a tail preserves order for free.
Hint 3 Use two dummy head nodes. Walk the original list once, appending each node to the matching tail. Then set the greater tail's next to None (crucial!) and connect the less tail to the greater dummy's first real node.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.