Back to DSA

Reverse Nodes in k-Group

hard
Acceptance: 43%
Linked List

Given 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 = 3
Output:[30,20,10,40,50]
Example 2:
Input:head = [10,20,30,40,50], k = 2
Output:[20,10,40,30,50]

Hints

00:00
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 complexityO(n)
Space complexityO(n/k)