Partition List - Problem

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.

Input & Output

Example 1 — Basic Partition
$ Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
💡 Note: Nodes with values less than 3 (1, 2, 2) come before nodes greater than or equal to 3 (4, 3, 5). Original relative order is preserved within each partition.
Example 2 — Single Element
$ Input: head = [2], x = 1
Output: [2]
💡 Note: Single node with value 2 is greater than x=1, so it remains in its position.
Example 3 — All Elements Same Side
$ Input: head = [1,1,1], x = 5
Output: [1,1,1]
💡 Note: All nodes have values less than x=5, 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
Partition List - Linked List Partitioning INPUT Original Linked List (x = 3) 1 4 3 2 5 2 null head = [1,4,3,2,5,2] x = 3 (partition value) Classification: Less than 3 Greater or Equal 1, 2, 2 4, 3, 5 Create two dummy heads: before after ALGORITHM STEPS 1 Create Two Lists before: nodes < x after: nodes >= x 2 Traverse Original Compare each node.val with partition value x 3 Append to Lists if val < x: add to before if val >= x: add to after 4 Connect Lists before.next = after.head after.next = null Processing Order: before: 1 --> 2 --> 2 after: 4 --> 3 --> 5 connect FINAL RESULT Partitioned Linked List: 1 2 2 4 3 5 null Output: [1, 2, 2, 4, 3, 5] Verification: OK All nodes < 3 come first: 1,2,2 All nodes >= 3 follow: 4,3,5 Relative order preserved: OK Complexity: Time: O(n) Space: O(1) Key Insight: Use two separate lists to collect nodes: one for values less than x, another for values greater than or equal to x. This two-pointer technique preserves the original relative order within each partition. Finally, connect the two lists by linking the tail of 'before' to the head of 'after' list. TutorialsPoint - Partition List | Optimal Two-Pointer Solution
Asked in
Amazon 45 Microsoft 30 Apple 25 Google 20
380.0K Views
Medium Frequency
~15 min Avg. Time
4.3K 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