You are given the head of a singly linked list and a number x. Rearrange the list so that every node whose value is less than x comes before every node whose value is x or more.
Inside each of the two groups, nodes must stay in the order they had in the original list. Return the head of the rearranged list.
Example 1
Input: head = [6, 2, 8, 1, 5, 3], x = 5 Output: [2, 1, 3, 6, 8, 5] Why: 2, 1, 3 are below 5; 6, 8, 5 keep their order
2 more examples and the constraints
Example 2
Input: head = [4, 4, 2], x = 4 Output: [2, 4, 4] Why: a value equal to x belongs to the second group
Example 3
Input: head = [], x = 0 Output: [] Why: nothing to move
Constraints
- 0 ≤ number of nodes ≤ 200
- −100 ≤ each node value ≤ 100
- −200 ≤ x ≤ 200
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy the values outO(n)
- Two lists, then joinO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work for a 200-node list | Verdict |
|---|---|---|---|
| Copy the values out | O(n) | Passes; O(n) extra memory | |
| Two lists, then join | O(n) | Best; one pass, O(1) space |
n = number of nodes. Both are linear; the second reads the list once and moves links, not values.
Edge cases to test
- Empty list. head is null: return null. Both dummies stay empty and before.next is null.
- Values equal to x. They go in the second group. [4, 4, 2] with x = 4 gives [2, 4, 4].
- Everything on one side. All nodes below x, or none: the other list is empty and the join still works.
- Already in order. [1, 2, 9, 8] with x = 5 comes back unchanged.
Common mistakes
- Forgetting to set the big tail's next to null, so the last node still points back into the list and makes a cycle.
- Sending values equal to x to the small list. Only strictly smaller values go first.
- Inserting nodes at the front of a list instead of at its tail, which reverses their order.
How to talk through it
- 1Clarify. Where do values equal to x go? Must the order inside each group stay the same? Can the list be empty?
- 2Give the simple version. Copy values into two arrays and write them back. Say it is O(n) but uses O(n) extra memory.
- 3Split the nodes instead. Two dummy heads with tail pointers; appending at the tail keeps the order.
- 4Code the join. Cut the big tail, then point the small tail at the big head. Say why the cut matters.
- 5Test out loud. Run the empty list, [4, 4, 2] with x = 4, and a list that is all on one side.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?