Friday, September 11, 2020

Reverse Nodes in k-Group

Problem: Given a linked list, reverse the nodes of a linked list k at a time and return its 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 left-out nodes in the end should remain as it is. 

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]


Approach: Same as Reverse a Linked List in groups of given size except we need to check if the remaining length is sufficient or not.


Implementation in C#:

    public ListNode ReverseKGroup(ListNode head, int k)
    {
        if (!this.IsSuffLength(head, k))
        {
            return head;
        }
        ListNode prev = null, next = null, curr = head;
        int count = 0;
        while (count < k)
        {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
            ++count;
        }
        if (next != null)
        {
            head.next = this.ReverseKGroup(next, k);
        }
        return prev;
    }
    private bool IsSuffLength(ListNode node, int k)
    {
        int i = 0;
        for (; node != null && i < k; ++i)
        {
            node = node.next;
        }
        if (i != k)
        {
            return false;
        }
        return true;
    }


Complexity: O(n)

No comments:

Post a Comment