Reverse Nodes in Even Length Groups

MediumLinked Listin-place reversal

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the head of a linked list. Split its nodes, in order, into consecutive groups whose intended sizes are 1, 2, 3, 4, .... The final group may be shorter than its intended size if the list runs out of nodes. Reverse the nodes of every group whose **actual** length is even, leave odd-length groups unchanged, and return the head of the modified list. Note that the last group is judged by how many nodes it really has, not by its intended size.

Examples

Input: head = [1,2,3,4,5,6,7,8]
Output: [1,3,2,4,5,6,8,7]
Groups are [1], [2,3], [4,5,6], [7,8]. The groups of length 2 are reversed.
Input: head = [1,1,0,6,5]
Output: [1,0,1,5,6]
Groups are [1], [1,0], [6,5]. The last group was meant to have 3 nodes but has 2, so it is reversed too.
Input: head = [2,1]
Output: [2,1]
Groups are [2] and [1]; both are odd length.

Constraints

  • 1 <= number of nodes <= 10^5
  • 0 <= Node.val <= 10^5

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More in-place reversal problems