Skip to content
HardLinked ListsAI interview only

Reverse Alternate K Groups

Asked atamazonmicrosoftadobe

01 · Problem

Given the head of a singly linked list and a positive integer k, process the list in consecutive groups of k nodes starting from the head: reverse the first group, leave the second group unchanged, reverse the third, leave the fourth unchanged, and so on.

If the list ends in the middle of a group, that partial group follows the same rule as a full one: it is reversed if it falls on a reversing turn and left as-is otherwise. Return the head of the modified list. Only links may change, not node values.

02 · Examples

Example 01
Input
head = [1,2,3,4,5,6,7,8,9], k = 3
Output
[3,2,1,4,5,6,9,8,7]

Group [1,2,3] is reversed, [4,5,6] is kept, and [7,8,9] is reversed.

Example 02
Input
head = [1,2,3,4,5,6,7], k = 2
Output
[2,1,3,4,6,5,7]

Reverse [1,2], keep [3,4], reverse [5,6], keep the partial group [7].

Example 03
Input
head = [1,2,3,4,5,6,7,8], k = 3
Output
[3,2,1,4,5,6,8,7]

Reverse [1,2,3], keep [4,5,6], and the partial group [7,8] falls on a reversing turn, so it becomes [8,7].

03 · Constraints

  • 01The number of nodes in the list is in the range [1, 104].
  • 021 <= k <= 104
  • 03-105 <= Node.val <= 105

04 · Optimal complexity

Time
O(n)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.