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
Original Train Formation:12345Group Identification:1G1 (Odd)2G2 (Even)3REVERSE4G3 (Odd)5After Reversing Even Groups:13245Odd Groups (No Change)Even Groups (Reversed)Final Result
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.
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
89.2K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen