Quant Memo
Coding/●●●●

Reverse a linked list in groups of k

Given the head of a singly linked list and an integer k, reverse the nodes k at a time and return the head. If the number of nodes is not a multiple of k, the final leftover group (fewer than k nodes) stays in its original order.

1 -> 2 -> 3 -> 4 -> 5,  k = 2   ->   2 -> 1 -> 4 -> 3 -> 5
1 -> 2 -> 3 -> 4 -> 5,  k = 3   ->   3 -> 2 -> 1 -> 4 -> 5

Do it in O(n)O(n) time and O(1)O(1) extra space. The recursive version is clean but uses O(n/k)O(n/k) stack; write the iterative one.

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions