Back to DSA
Reverse Nodes in k-Group
hardGiven the head of a singly linked list and a positive integer k, reverse the order of every consecutive group of k nodes. If the remaining nodes at the tail number fewer than k, leave them in their original order. Return the modified list.
Examples
Example 1:
Input:
head = [10,20,30,40,50], k = 3Output:
[30,20,10,40,50] Example 2:
Input:
head = [10,20,30,40,50], k = 2Output:
[20,10,40,30,50]Hints
class Solution {
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 = reverseKGroup(curr, k);
while (count-- > 0) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}Time complexity
O(n)Space complexity
O(n/k)