Linked List Partitioner - Problem

Given a linked list and a value x, partition it such that all nodes with values less than x come before all nodes with values greater than or equal to x.

Important: You should preserve the original relative order of the nodes in each of the two partitions.

Return the head of the modified linked list.

Input & Output

Example 1 — Basic Partition
$ Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
💡 Note: Values less than 3 (1,2,2) come first, followed by values >= 3 (4,3,5). Original relative order is preserved within each group.
Example 2 — All Values Greater
$ Input: head = [2,1], x = 2
Output: [1,2]
💡 Note: Only value 1 is less than 2, so it comes first, followed by value 2.
Example 3 — Single Node
$ Input: head = [1], x = 2
Output: [1]
💡 Note: Single node case: 1 < 2, so the list remains unchanged.

Constraints

  • The number of nodes in the list is in the range [0, 200]
  • -100 ≤ Node.val ≤ 100
  • -200 ≤ x ≤ 200

Visualization

Tap to expand
INPUTALGORITHMRESULTLinked List & Partition ValueTwo Dummy Heads ApproachPartitioned List143252Partition Value: x = 31Step 1Create two dummy heads2Step 2Route nodes to chains3Step 3Connect before to after4Step 4Return new head122435Values < 3: [1,2,2]Values >= 3: [4,3,5]Final: [1,2,2,4,3,5]!Key Insight:Building two separate chains simultaneously (using dummy heads) eliminatesthe need for extra storage and allows single-pass partitioning with O(1) space.TutorialsPoint - Linked List Partitioner | Two Dummy Heads Approach
Asked in
Amazon 45 Microsoft 32 Apple 28 Google 25
78.5K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen