25. Reverse Nodes in k-Group
hardReverse a linked list in chunks of size k, leaving any leftover tail of length less than k alone. Tests pointer-rewiring under structured boundaries — easy to over-engineer with recursion, hard to nail iteratively.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Constraints
The number of nodes in the list is n.1 <= k <= n <= 50000 <= Node.val <= 1000
Examples
Example 1
head = [1,2,3,4,5], k = 2[2,1,4,3,5]Example 2
head = [1,2,3,4,5], k = 3[3,2,1,4,5]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Decompose: (1) check there are at least k nodes ahead; (2) reverse the next k; (3) recurse / loop on the remainder.
Hint 2
Use a dummy head to simplify the 'connect the previous group's tail to the new group's head' step.
Hint 3
For O(1) space, do this iteratively with a groupPrev pointer tracking the boundary between the most-recently-reversed group and the next one.
Solution approach
Reveal approach
Iterative grouping with a boundary pointer. Use a dummy head; let groupPrev start at dummy. In a loop: walk k steps from groupPrev to find the kth node (kth). If there's no kth node (fewer than k remain), break — the rest stays as-is. Save groupNext = kth.next. Reverse the segment from groupPrev.next to kth using the standard three-pointer reversal with stop = groupNext. Then rewire: tmp = groupPrev.next; groupPrev.next = kth; tmp.next becomes the new groupPrev for the next iteration. Continue until done. Return dummy.next. O(n) time, O(1) extra space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- linked-list
- reversal
- pointer-rewiring
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
- Microsoft
Practice these live with InterviewChamp.AI
Drill Reverse Nodes in k-Group and Linked Lists problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →