Mid/SeniorLinked List

Reverse Nodes in Even Length Groups

You are given the head of a linked list.

The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words:

  • The 1^st node is assigned to the first group.
  • The 2^nd and the 3^rd nodes are assigned to the second group.
  • The 4^th, 5^th, and 6^th nodes are assigned to the third group, and so on.

Note that the length of the last group may be less than or equal to 1 + the length of the second to last group.

Reverse the nodes in each group with an even length, and return the head of the modified linked list.

Example 1
[5] -> [2] -> [6] -> [3] -> [9] -> [1] -> [7] -> [3] -> [8] -> [4] -> null
---
[5] -> [6] -> [2] -> [3] -> [9] -> [1] -> [4] -> [8] -> [3] -> [7] -> null
Inputhead = [5,2,6,3,9,1,7,3,8,4]
Output[5,6,2,3,9,1,4,8,3,7]
The first and third groups have odd lengths and are unchanged, while the second group [2, 6] and last group [7, 3, 8, 4] have even lengths and are reversed.
Example 2
[1] -> [1] -> [0] -> [6] -> null
---
[1] -> [0] -> [1] -> [6] -> null
Inputhead = [1,1,0,6]
Output[1,0,1,6]
The first and last groups have length 1 and are unchanged, while the second group [1, 0] has even length and is reversed.

Constraints

  • The number of nodes in the list is in the range [1, 10^5].
  • 0 <= Node.val <= 10^5

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate