Reverse the Order of K-Groups
Given the head of a singly linked list and an integer k >= 1, cut the list into consecutive groups of k nodes, starting from the head; the last group may be shorter. Reverse the order of the groups while keeping the nodes inside each group in their original order, and return the new head.
k = 3: 1 -> 2 -> 3 -> 4 -> 5 -> 6 becomes 4 -> 5 -> 6 -> 1 -> 2 -> 3 k = 3: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 becomes 7 -> 4 -> 5 -> 6 -> 1 -> 2 -> 3 k = 1: 1 -> 2 -> 3 becomes 3 -> 2 -> 1
Nodes are objects of the form { val, next }, with next set to null at the end. Relink the existing nodes; use O(1) extra space. In the interview you build the list and the test scaffolding yourself.
Hints
Hint 1
Clarify which reversal is wanted before writing anything. The well-known problem reverses the nodes inside every group; this one moves whole groups.
Hint 2
You never need to touch the links inside a group. Only each group's last next pointer changes.
Hint 3
Walk the list one group at a time, and attach everything collected so far behind the group you just cut off.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.