1325. Radix-Sorted Chain
A ticket queue is kept as a singly linked list of non-negative priority numbers, and the system must sort it without copying values into an array. Given the head of the list, sort it in ascending order using least-significant-digit radix sort in base 10: on each pass, relink the existing nodes into ten digit queues (queue d receives the nodes whose current digit is d, in the order they are met, so the pass is stable), then join the queues from digit 0 to digit 9. Reuse the original nodes instead of allocating new ones.
Return the new head, or null for an empty list. The list may hold up to 100000 nodes, so write it iteratively with no recursion. Aim for O(n * d) time, where d is the number of digits of the largest value, and O(1) extra space beyond the ten queue pointers.
Example 1
- Input:
- head = [38,5,912,47,5,300]
- Output:
- [5,5,38,47,300,912]
- Explanation:
The values in ascending order are 5, 5, 38, 47, 300, 912; the two 5 nodes stay together.
Example 2
- Input:
- head = [7,3,5]
- Output:
- [3,5,7]
- Explanation:
A short list sorted ascending gives 3, 5, 7.
Example 3
- Input:
- head = [100,10,1,0]
- Output:
- [0,1,10,100]
- Explanation:
Powers of ten and zero need up to four passes; the sorted list is 0, 1, 10, 100.
Constraints
- 0 ≤ n ≤ 105
- 0 ≤ node.val ≤ 109
- An iterative solution is required
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n * d)
- Space
- O(1)