LINK-P4

Turn each group round

Practice 4 of 6Linked lists8 tests

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.
  • k is 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Groups of threeNot run
2Groups of twoNot run
3k is 1Not run
4k is the lengthNot run
5k is more than the lengthNot run
6EmptyNot run
7Same nodesNot run
8100,000 nodesNot run