Reverse Nodes in k-Group

Hard · Linked Lists · Linked List · Recursion

Problem

Given the head of a linked list and a positive integer k, reverse the nodes in consecutive groups of k. If fewer than k nodes remain at the end, leave that final group in its original order.

Rearrange the nodes themselves rather than only changing their values, and return the head of the modified list.

Can you do it with O(1) extra memory?

Examples

Input: head = [1,2,3,4,5,6,7,8], k = 3
Output: [3,2,1,6,5,4,7,8]

Two full groups of three are reversed; the leftover 7, 8 stays as it is.

Input: head = [9,8,7], k = 1
Output: [9,8,7]

Reversing a group of one changes nothing.

Constraints

Approaches

Follow-up

What if the short last group should be reversed too, or only every other group? Both keep the same stitching and change only when to reverse: see the use cases “Reverse every group, short one included” and “Reverse every other group”.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…