Alternate reversal of linked list in groups of size k
Filed under Amazon
Free read 2 of 3Confirm behavior when the remaining nodes are fewer than k (usually leave them as is).
The question
Given a linked list and an integer k, reverse every other group of k nodes. For example, if k=2, reverse the first 2 nodes, skip the next 2, reverse the next 2, and so on.
Constraints
- 1 <= k <= list length
- List nodes are non-null
- Time complexity: O(n)
- Space complexity: O(1) or O(n/k) recursion
Examples
- Input
- 1->2->3->4->5->6, k=2
- Output
- 2->1->3->4->6->5
- Why
- Reverse (1,2), keep (3,4), reverse (5,6).
Approach
Confirm behavior when the remaining nodes are fewer than k (usually leave them as is).
Use a helper function to reverse k nodes. Alternate between calling the reverse function and a skip function.
Maintain 'prev' and 'curr' pointers to stitch the segments together after each operation.
Handle empty lists or k=1 cases where no changes occur.
Tips
- What they are testing: Test with k=1, k=list length, and list length not divisible by k.
- Common mistake: Failing to correctly reconnect the tail of the reversed segment to the head of the skipped segment.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.