KatInterview

25. Reverse Nodes in k-Group

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to reverse a linked list in segments of size k. If the number of nodes at the end of the list is less than k, these nodes should be left in their original order. This is a classic linked list manipulation problem that involves careful pointer management to reverse sublists and stitch them back together.

Solution

Reverse Nodes in k-Group in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head or k == 1:
            return head

        dummy = ListNode(0, head)
        group_prev = dummy

        while True:
            # 1. Check if there's a group of k nodes.
            group_tail = group_prev
            for _ in range(k):
                group_tail = group_tail.next
                if not group_tail:
                    return dummy.next # Not enough nodes, we are done.

            # We have a group to reverse.
            group_head = group_prev.next
            next_group_head = group_tail.next

            # 2. Reverse the group.
            # Disconnect the group to reverse it.
            group_tail.next = None

            # Standard iterative reversal.
            prev, curr = None, group_head
            while curr:
                next_temp = curr.next
                curr.next = prev
                prev, curr = curr, next_temp
            # After reversal, `prev` is the new head of the group (original group_tail).

            # 3. Reconnect the list.
            group_prev.next = prev  # `prev` is the new head.
            group_head.next = next_group_head  # `group_head` is the new tail.

            # 4. Move to the next group.
            group_prev = group_head

Reverse Nodes in k-Group in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k == 1) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode groupPrev = dummy;

        while (true) {
            // 1. Check if there's a group of k nodes.
            ListNode groupTail = groupPrev;
            for (int i = 0; i < k; i++) {
                groupTail = groupTail.next;
                if (groupTail == null) {
                    return dummy.next; // Not enough nodes, we are done.
                }
            }

            // We have a group to reverse.
            ListNode groupHead = groupPrev.next;
            ListNode nextGroupHead = groupTail.next;

            // 2. Reverse the group.
            // Disconnect the group to reverse it.
            groupTail.next = null;

            // Standard iterative reversal.
            ListNode prev = null;
            ListNode curr = groupHead;
            while (curr != null) {
                ListNode nextTemp = curr.next;
                curr.next = prev;
                prev = curr;
                curr = nextTemp;
            }
            // After reversal, prev is the new head of the group (original groupTail).
            
            // 3. Reconnect the list.
            groupPrev.next = prev; // `prev` is the new head.
            groupHead.next = nextGroupHead; // `groupHead` is the new tail.

            // 4. Move to the next group.
            groupPrev = groupHead;
        }
    }
}

Reverse Nodes in k-Group in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head || k == 1) {
            return head;
        }

        ListNode dummy(0);
        dummy.next = head;
        ListNode* groupPrev = &dummy;

        while (true) {
            // 1. Check if there's a group of k nodes.
            ListNode* groupTail = groupPrev;
            for (int i = 0; i < k; ++i) {
                groupTail = groupTail->next;
                if (!groupTail) {
                    return dummy.next; // Not enough nodes, we are done.
                }
            }

            // We have a group to reverse.
            ListNode* groupHead = groupPrev->next;
            ListNode* nextGroupHead = groupTail->next;

            // 2. Reverse the group.
            // Disconnect the group to reverse it.
            groupTail->next = nullptr;
            
            // Standard iterative reversal of the group starting at groupHead.
            ListNode* prev = nullptr;
            ListNode* curr = groupHead;
            while (curr) {
                ListNode* nextTemp = curr->next;
                curr->next = prev;
                prev = curr;
                curr = nextTemp;
            }
            // After reversal, `prev` is the new head of the group (original groupTail).

            // 3. Reconnect the list.
            groupPrev->next = prev; // `prev` is the new head.
            groupHead->next = nextGroupHead; // `groupHead` is the new tail.

            // 4. Move to the next group.
            groupPrev = groupHead;
        }

        return dummy.next; // Logically unreachable.
    }
};

Reverse Nodes in k-Group in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseKGroup(head: ListNode | null, k: number): ListNode | null {
    if (!head || k === 1) {
        return head;
    }

    const dummy = new ListNode(0, head);
    let groupPrev: ListNode | null = dummy;

    while (true) {
        // 1. Check if there's a group of k nodes.
        let groupTail: ListNode | null = groupPrev;
        for (let i = 0; i < k; i++) {
            if (groupTail) {
                groupTail = groupTail.next;
            }
            if (!groupTail) {
                return dummy.next; // Not enough nodes, we are done.
            }
        }
        
        // We have a group to reverse.
        const groupHead = groupPrev.next;
        const nextGroupHead = groupTail.next;
        
        // 2. Reverse the group.
        // Disconnect the group to reverse it.
        groupTail.next = null;
        
        let prev: ListNode | null = null;
        let curr: ListNode | null = groupHead;
        while (curr) {
            const nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        // After reversal, `prev` is the new head of the group (original groupTail).
        
        // 3. Reconnect the list.
        groupPrev.next = prev; // `prev` is the new head.
        if (groupHead) {
            groupHead.next = nextGroupHead; // `groupHead` is the new tail.
        }
        
        // 4. Move to the next group.
        groupPrev = groupHead;
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.