The problem
Split the list into groups of k nodes, starting at the head. Reverse the nodes inside each full group. If the last group has fewer than k nodes, leave it as it is. Return the head of the whole list.
list 1, 2, 3, 4, 5, 6, 7, 8, k 3 -> 3, 2, 1, 6, 5, 4, 7, 8
list 1, 2, 3, 4, 5, 6, k 2 -> 2, 1, 4, 3, 6, 5
list 1, 2, 3, k 5 -> 1, 2, 3
The tests build the list from nodes with a value and a next, pass you the head, then walk from the head you return, following next, and compare the values they find. An empty list is None.
Relink the nodes you are given; do not copy values into new nodes. Use O(1) extra space.
Limits
- Up to 100,000 nodes.
kis at least 1.
Builds on LINK-4 Reversing.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Groups of three | Not run | |
| 2 | Groups of two | Not run | |
| 3 | k is 1 | Not run | |
| 4 | k is the length | Not run | |
| 5 | k is more than the length | Not run | |
| 6 | Empty | Not run | |
| 7 | Same nodes | Not run | |
| 8 | 100,000 nodes | Not run |