~/DHRUVUpskilling
← board/DSA/In place reversal LinkedList/dsa-in-place-reversal-linkedlist-02
Revision 1·28 Sept

Reverse Nodes in k-Group

DifficultyHard
PatternIn place reversal LinkedList
TrackDSA
tl;dr

The task is to reverse the nodes in groups of k

full write-up

The task is to reverse the nodes in groups of k in a given linked list, where k is a positive integer, and at most the length of the linked list. If any remaining nodes are not part of a group of k, they should remain in their original order.

It is not allowed to change the values of the nodes in the linked list. Only the order of the nodes can be modified.

Note: Use only O(1) extra memory space.

Constraints

Let n be the number of nodes in a linked list.

  • 1 ≤ k ≤ n ≤ 500
  • 0 ≤ Node.value ≤ 1000

Examples

Example 1

Input: head = [1, 2, 3, 4, 5, 6, 7, 8] k = 3

Explanation:

  • First group of 3: [1, 2, 3] → reversed to [3, 2, 1]
  • Second group of 3: [4, 5, 6] → reversed to [6, 5, 4]
  • Remaining nodes [7, 8] are fewer than k, so they stay in original order.

Output: [3, 2, 1, 6, 5, 4, 7, 8]


Example 2

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

Explanation:

  • First group of 2: [1, 2] → reversed to [2, 1]
  • Second group of 2: [3, 4] → reversed to [4, 3]
  • Remaining node [5] is fewer than k, so it stays as is.

Output: [2, 1, 4, 3, 5]

Solution Aim is to reverse k groups, to do that I'll start by creating a dummy node and point it to head. I'll create a pointer ptr and point it to dumjmy node. I'll use a tracker ptr that'll move k terms forward and reverse back of it.

Once we reverse we'll return prev , curr , now lastNodeOfReversed will be ptr.next , Now we just need to do some connection.

so ptr.next will connect with prev, lastNodeOfReversed.next will connect with curr, ptr= lastNodeOfREversed.

will continue doing this unless ptr is pointing to null

var reverseKGroup = function (head, k) {

    let dummy = new ListNode(0, head);

    let prev = dummy;
    let curr = dummy.next;

    function reverseK(head, k) {
        let prev = null;
        let curr = head;
        let next = null;

        let temp = head;

        while (curr !== null && k > 0) {
            next = curr.next;

            curr.next = prev;
            prev = curr;
            curr = next;
            k--;

        }

        return [prev, curr];
    }

    while (curr !== null) {


        let currentHead = curr;


        let tracker = curr;

        for (let i = 1; i < k; i++) {
            if (tracker === null) {
                break;
            }
            tracker = tracker.next;
        }

        if (tracker === null) {
            break;
        }

        let [reversedHead, nextElement] = reverseK(curr, k);

        prev.next = reversedHead;
        currentHead.next = nextElement;
        prev = curr;
        curr = nextElement;



        //node will be pointing to next group;



    }

    return dummy.next

};

Reverse Nodes in k-Group — pattern notes — Dhruv Parmar