Partition List - Problem
Partition List is a classic linked list manipulation problem that tests your ability to reorganize nodes while preserving order.

You are given the head of a singly linked list and a pivot value x. Your task is to partition the list such that:

  • All nodes with values less than x come before nodes with values greater than or equal to x
  • The original relative order of nodes in each partition must be preserved

Think of it like organizing a line of people by height while keeping friends together in their original order within each height group!

Example: Given list 1→4→3→2→5→2 and x = 3, the result should be 1→2→2→4→3→5

Input & Output

example_1.py — 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 first in their original order, followed by nodes with values ≥ 3 (4,3,5) in their original order.
example_2.py — All Elements Same Side
$ Input: head = [2,1], x = 2
Output: [1,2]
💡 Note: Node with value 1 < 2 comes first, followed by node with value 2 ≥ 2.
example_3.py — Single Node
$ Input: head = [1], x = 2
Output: [1]
💡 Note: Single node case: since 1 < 2, the node stays in place as the only element in the 'smaller' partition.

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
Two Chain Building VisualizationPartition threshold: x = 3Phase 1: Initialize Two ChainsbeforedummyafterdummyPhase 2: Build Chains (< 3 vs ≥ 3)dummy122Before Chain (values < 3)dummy435nullAfter Chain (values ≥ 3)Phase 3: Connect Chains2last in before4first in afterCONNECTPhase 4: Final Partitioned List122435✅ Partitioned: All < 3 before all ≥ 3, original order preserved💡 Key InsightDummy nodes eliminate edge cases!• No need to track first/last nodes• Simplified pointer management• Clean connection logic• O(1) space, O(n) time
Understanding the Visualization
1
Setup Phase
Create two dummy heads - one for shorter students (< height x) and one for taller students (≥ height x)
2
Sorting Phase
Go through each student and direct them to the appropriate line while maintaining their position relative to friends
3
Connection Phase
Connect the end of the shorter students line to the beginning of the taller students line
4
Final Result
Remove dummy heads and return the combined line with proper partitioning
Key Takeaway
🎯 Key Insight: Using dummy heads transforms complex edge case handling into simple chain building, making the code cleaner and more reliable.
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 18
73.5K Views
Medium Frequency
~15 min Avg. Time
1.8K 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