Partition List
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ number of nodes in head ≤ 200 - ◆
-1000 ≤ node value, x ≤ 1000
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Collect into Two Lists, Then Write Back
GoodWalk the list once, sorting every value into one of two arrays based on whether it's less than x or not. Concatenate the less-than values before the rest, then walk the list a second time, overwriting each node's value in that new order. Correct, but the two arrays cost O(n) extra space where the optimal solution needs none.
O(n)O(n)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node partition(Node head, int x) {
9 List<Integer> less = new ArrayList<>();
10 List<Integer> geq = new ArrayList<>();
11 Node curr = head;
12 while (curr != null) {
13 if (curr.val < x) {
14 less.add(curr.val);
15 } else {
16 geq.add(curr.val);
17 }
18 curr = curr.next;
19 }
20 List<Integer> combined = new ArrayList<>(less);
21 combined.addAll(geq);
22 curr = head;
23 for (int v : combined) {
24 curr.val = v;
25 curr = curr.next;
26 }
27 return head;
28 }
29}Optimal — Build Two Chains with Dummy Heads
OptimalGrow two separate chains while walking the list once: a "less" chain and a "greater-or-equal" chain, each anchored by its own dummy head so the very first real node appended works the same way as every later one. Every visited node gets appended to whichever chain it belongs in and becomes that chain's new tail — no values are copied, the existing nodes are simply relinked. Once every node has been placed, the less chain's tail is pointed at the geq chain's head, the geq chain's tail is terminated with null, and the less chain's dummy-following node is the new head.
O(n)O(1)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node partition(Node head, int x) {
9 Node lessDummy = new Node(0);
10 Node geqDummy = new Node(0);
11 Node lessTail = lessDummy;
12 Node geqTail = geqDummy;
13 Node curr = head;
14 while (curr != null) {
15 if (curr.val < x) {
16 lessTail.next = curr;
17 lessTail = curr;
18 } else {
19 geqTail.next = curr;
20 geqTail = curr;
21 }
22 curr = curr.next;
23 }
24 geqTail.next = null;
25 lessTail.next = geqDummy.next;
26 return lessDummy.next;
27 }
28}