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
Understanding the Visualization
1
Group Formation
Cars are grouped: [Car1], [Car2,Car3], [Car4,Car5,Car6], [Car7,Car8,Car9,Car10]
2
Identify Even Groups
Groups 2 and 4 have even lengths (2 and 4 respectively), so they need reversal
3
Reverse Even Groups
Group 2: [Car2,Car3] โ [Car3,Car2], Group 4: [Car7,Car8,Car9,Car10] โ [Car10,Car9,Car8,Car7]
4
Final Order
Result: [Car1] โ [Car3,Car2] โ [Car4,Car5,Car6] โ [Car10,Car9,Car8,Car7]
Key Takeaway
๐ฏ Key Insight: Process groups incrementally in one pass - when you identify a complete even-length group, reverse it immediately rather than storing for later processing. This maintains O(n) time complexity while using O(1) space.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code