Reverse Nodes In K Group
Hard · Linked List
You are given the head of a singly linked list and an integer k. Reverse the nodes of the list k at a time and return the new head. Walk along the list splitting it into consecutive chunks of k nodes each and reverse the links within every full chunk, but if the nodes remaining at the end are fewer than k, leave that final partial chunk exactly as it was found.
Examples
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Why: Nodes are reversed two at a time; the leftover single node 5 has no partner so it stays as is.
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Why: The first three nodes form a full group and get reversed; the remaining 4,5 form an incomplete group of size 2 so they are left untouched.
Input: head = [1,2,3,4,5,6], k = 1
Output: [1,2,3,4,5,6]
Why: Groups of size 1 reversed individually produce the same order.
Constraints
1 <= number of nodes <= 5000, -1000 <= node value <= 1000, 1 <= k <= number of nodes
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Reverse Nodes In K Group
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Reverse Nodes In K Group. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.