A singly linked list starts at the node head. Put its nodes in increasing order using insertion sort, and return the node that comes first afterwards.
Insertion sort keeps a sorted part that starts with one node. It takes the remaining nodes one by one and places each where it fits in the sorted part, until nothing is left to place.
Example 1
Input: head = [3, 5, 1, 4] Output: [1, 3, 4, 5] Why: 1 moves to the front, 4 slots in before 5
2 more examples and the constraints
Example 2
Input: head = [-2, 7, 0, 7, -5] Output: [-5, -2, 0, 7, 7] Why: equal values end up next to each other
Example 3
Input: head = [8] Output: [8] Why: one node is already sorted
Constraints
- 1 ≤ number of nodes ≤ 5,000
- −5,000 ≤ each node value ≤ 5,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Insert each node, walking from the frontO(n²)
- Insertion sort with a tail checkO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work on a sorted list of 5,000 nodes | Verdict |
|---|---|---|---|
| Insert each node, walking from the front | O(n²) | Passes; slowest on sorted input | |
| Insertion sort with a tail check | O(n²) | Best; sorted runs cost nothing |
n = number of nodes. On random input both do about n²/4 steps; the tail check wins on input that is already mostly in order.
Edge cases to test
- One node. [8] is returned as it is.
- Already sorted. With the tail check this is a single pass; without it, the slowest input.
- Reverse order. Every node moves to the very front, right after the dummy.
- Equal values. [7, 7, 7] must stay three nodes long; no node is lost or linked twice.
Common mistakes
- Splicing a node in before saving
node.next, which cuts off the rest of the input. - Inserting at the head without a dummy node, which needs a special case and is easy to get wrong.
- Forgetting to unhook the node first, which leaves a loop in the list.
How to talk through it
- 1Clarify. Must I relink nodes, or may I swap values? Can the list be empty?
- 2Describe insertion sort. A sorted front part grows by one node each round; each node goes to its place.
- 3Use a dummy. A node before the head makes inserting at the front the same as anywhere else.
- 4Add the tail check. A node not smaller than the tail is already in place, so sorted input runs in O(n).
- 5Test out loud. Run one node, a reversed list and a list with repeated values.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?