Reverse Nodes in k-Group
Given the head of a linked list, reverse every k nodes as a group. If remaining nodes < k, leave them as-is.
Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: Groups of 2: [1,2]→[2,1], [3,4]→[4,3], [5] stays.
Output: [2,1,4,3,5]
Explanation: Groups of 2: [1,2]→[2,1], [3,4]→[4,3], [5] stays.
Example 2
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Output: [3,2,1,4,5]
Solution Approach
Count k nodes; if fewer remain, stop. Reverse the group of k, then recurse on the rest.
- Check if k nodes exist from current position
- Reverse k nodes iteratively
- Recursively process remainder
Java
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count < k) { curr = curr.next; count++; }
if (count < k) return head;
ListNode prev = null, node = head;
for (int i = 0; i < k; i++) {
ListNode next = node.next;
node.next = prev;
prev = node;
node = next;
}
head.next = reverseKGroup(node, k);
return prev;
}
Complexity Analysis:
Time complexity: O(n)
Space complexity: O(n/k). Recursion stack depth