AAlgoLoopSpaced repetition for LeetCode
HARDLinked ListLeetCode ↗

Reverse Nodes in k-Group

The key idea

Reverse each block of k nodes in place, but only after you confirm a full group of k exists ahead. Keep a prev_group_tail that points at the last node of the already-finished part, so each reversed block can be stitched back onto the chain in the right order.

Problem

Given the head of a linked list, reverse the nodes of the list k at a time and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, then the nodes that are left out at the end should remain as is.

You may not alter the values in the list's nodes — only the nodes themselves may be changed.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems