โ† Back to Index

๐Ÿ“š Reverse Nodes in k-Group โ€“ Java Cheat Sheet (One Page)

๐Ÿ“Œ What Is It?

The Reverse Nodes in k-Group problem involves reversing nodes of a linked list in groups of size k. If the number of nodes is not a multiple of k, the remaining nodes are left as is.

๐Ÿงฑ Pattern Template

public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null || k == 1) return head;

    // Dummy node to simplify edge cases
    ListNode dummy = new ListNode(0);
    dummy.next = head;

    ListNode prevGroupEnd = dummy;

    while (true) {
        // Find the kth node
        ListNode kth = getKthNode(prevGroupEnd, k);
        if (kth == null) break;

        // Reverse the group
        ListNode groupStart = prevGroupEnd.next;
        ListNode nextGroupStart = kth.next;

        // Reverse the current group
        reverse(groupStart, kth);

        // Connect the reversed group
        prevGroupEnd.next = kth;
        groupStart.next = nextGroupStart;

        // Move to the next group
        prevGroupEnd = groupStart;
    }

    return dummy.next;
}

private ListNode getKthNode(ListNode curr, int k) {
    while (curr != null && k > 0) {
        curr = curr.next;
        k--;
    }
    return curr;
}

private void reverse(ListNode start, ListNode end) {
    ListNode prev = null, curr = start, next = null;
    while (prev != end) {
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
}

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Reverse Nodes in k-Group

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: The nodes are reversed in groups of 2.

๐Ÿ’ก Pro Tips