You are given the head of a singly linked list of integers. Rearrange it so the values run from smallest to largest, and return the head of the sorted list.
Try to do it in O(n log n) time while using only a constant amount of extra memory.
Example 1
Input: head = [5, 1, 4, 2] Output: [1, 2, 4, 5] Why: the same nodes, in increasing order
2 more examples and the constraints
Example 2
Input: head = [0, -3, 7, -3, 2] Output: [-3, -3, 0, 2, 7] Why: equal values sit next to each other
Example 3
Input: head = [] Output: [] Why: an empty list is already sorted
Constraints
- 0 ≤ number of nodes ≤ 50,000
- −100,000 ≤ each node value ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy, sort, write backO(n log n)
- Merge sort, recursiveO(n log n)
- Merge sort, bottom upO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 50,000 nodes | Verdict |
|---|---|---|---|
| Copy, sort, write back | O(n log n) | Passes; O(n) memory | |
| Merge sort, recursive | O(n log n) | Passes; O(log n) stack | |
| Merge sort, bottom up | O(n log n) | Best; O(1) memory |
n = number of nodes. All three take O(n log n) time; they differ in the extra memory they need.
Edge cases to test
- Empty list. Return null. The bottom-up loop never runs because length is 0.
- One node. Already sorted; return it unchanged.
- Odd length. With 5 nodes, the last run of a pass may be shorter than width, or have no partner at all. split must return null instead of crashing.
- Repeated values. Using ≤ when comparing keeps equal values in their original order and still sorts correctly.
- Already sorted or reversed. Merge sort does the same O(n log n) work on any order; there is no bad case like quicksort has.
Common mistakes
- Finding the middle with
fast = headinstead ofhead.next, so a 2-node list never splits and the recursion never ends. - Forgetting to cut the list (
slow.next = Noneor the cut in split), so the two halves are still joined. - Not moving
tailto the end of each merged run, so the next merge overwrites links that were already made.
How to talk through it
- 1Clarify. May I change node values, or must I relink nodes? Is O(log n) recursion stack acceptable?
- 2State the easy answer. Copy to an array and sort: O(n log n) time but O(n) memory.
- 3Pick merge sort. It needs only forward walks, and merging two lists needs no extra memory.
- 4Go bottom up. Explain passes of width 1, 2, 4 and the split and merge helpers that each pass uses.
- 5Test out loud. Run the empty list, one node, and an odd length like [0, -3, 7, -3, 2].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?