Reverse Nodes in Even Length Groups - Problem
You're given the head of a linked list and need to perform a fascinating grouping and reversal operation!
Here's how the grouping works:
- Nodes are divided into sequential groups with lengths following the natural number sequence: 1, 2, 3, 4, 5, ...
- Group 1: Contains 1 node (the 1st node)
- Group 2: Contains 2 nodes (the 2nd and 3rd nodes)
- Group 3: Contains 3 nodes (the 4th, 5th, and 6th nodes)
- And so on...
Important note: The last group might be incomplete if there aren't enough remaining nodes.
Your task: Reverse the nodes in each group that has an even length, then return the head of the modified linked list.
For example, if a group has 2 nodes (even), reverse them. If a group has 3 nodes (odd), leave them unchanged.
Input & Output
example_1.py — Basic Case
$
Input:
head = [5,2,6,3,9,1,7,3,8,4]
›
Output:
[5,6,2,3,9,1,4,8,3,7]
💡 Note:
Groups: [5], [2,6], [3,9,1], [7,3,8,4]. Group 2 (size 2) and group 4 (size 4) are even, so they get reversed: [5] → [6,2] → [3,9,1] → [4,8,3,7]
example_2.py — Small List
$
Input:
head = [1,1,0,6]
›
Output:
[1,0,1,6]
💡 Note:
Groups: [1], [1,0], [6]. Only group 2 has even length (2), so reverse it: [1] → [0,1] → [6] = [1,0,1,6]
example_3.py — Single Node
$
Input:
head = [2]
›
Output:
[2]
💡 Note:
Only one group of size 1 (odd), so no changes are made.
Constraints
- The number of nodes in the list is in the range [1, 105]
- 1 ≤ Node.val ≤ 106
- The linked list is guaranteed to have at least one node
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code