Reverse Nodes In Even Length Groups

Reverse each natural-numbered group of nodes whose length is even.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
linked-list

Problem#

Groups have lengths 1, 2, 3, 4, … but the last group may be shorter. For each group whose actual length is even, reverse it in place.

Examples#

  • [5,2,6,3,9,1,7,3,8,4][5,6,2,3,9,1,4,8,3,7]

Constraints#

  • Length in [1, 10^5].

Hints#

Hint 1
Walk one group at a time; measure its actual length first, reverse iff even.

Approach#

Track groupSize. For each group, count how many nodes are actually present (could be less than groupSize for the last group). If that count is even, reverse those nodes in place using the head-insertion trick.

Solution#

Reverse Nodes In Even Length Groups
class Solution {
public:
ListNode* reverseEvenLengthGroups(ListNode* head) {
ListNode dummy(0, head);
ListNode* pre = &dummy;
int groupSize = 1;
while (pre->next) {
int count = 0;
ListNode* p = pre;
for (int i = 0; i < groupSize && p->next; ++i) { p = p->next; ++count; }
if (count % 2 == 0) {
ListNode* curr = pre->next;
for (int i = 0; i < count - 1; ++i) {
ListNode* mover = curr->next;
curr->next = mover->next;
mover->next = pre->next;
pre->next = mover;
}
pre = curr;
} else {
pre = p;
}
++groupSize;
}
return dummy.next;
}
};

Editorial#

Same head-insertion technique as Reverse Linked List II, but applied selectively. pre always points one node before the current group’s start, so after handling the group, advance it to the group’s tail (the new tail after possible reversal). The actual count check is crucial — the problem keys on the actual group length, not the natural number i.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.