1340. Three-Band Chain
A train depot stores freight cars as a singly linked list, where each node carries the load weight in val. Before departure the cars must be grouped into three bands around the integer pivot: first every car lighter than pivot, then every car whose weight equals pivot, then every car heavier than pivot.
Inside each band the cars must keep the relative order they had in the input list. Relink the existing nodes instead of creating new ones, and return the head of the rearranged list, or null when the list is empty. Aim for O(n) time and O(1) extra space.
Example 1
- Input:
- head = [5,1,3,3,8,2], pivot = 3
- Output:
- [1,2,3,3,5,8]
- Explanation:
Weights below 3 are 1 and 2, the weights equal to 3 are 3 and 3, and the heavier ones are 5 and 8, each band keeping input order, giving [1, 2, 3, 3, 5, 8].
Example 2
- Input:
- head = [4,9,4,1], pivot = 4
- Output:
- [1,4,4,9]
- Explanation:
The lighter band is [1], the equal band is [4, 4] and the heavier band is [9], giving [1, 4, 4, 9].
Example 3
- Input:
- head = [], pivot = 7
- Output:
- []
- Explanation:
An empty list stays empty, so the result is null.
Constraints
-
0 ≤ n ≤ 1000, wherenis the number of nodes -
-109 ≤ node.val, pivot ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)