#2074
Medium Algorithms Reverse nodes in even length groups
Linked List
63.7% acceptance
Feb 25, 2026
870
375
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 1st node is assigned to the first group.
The 2nd and the 3rd nodes are assigned to the second group.
The 4th, 5th, and 6th 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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn reverse_even_length_groups(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// Collect all values
let mut vals = Vec::new();
let mut cur = &head;
while let Some(node) = cur {
vals.push(node.val);
cur = &node.next;
}
// Process groups
let n = vals.len();
let mut idx = 0;
let mut group = 1;
while idx < n {
let end = (idx + group).min(n);
let actual_len = end - idx;
if actual_len % 2 == 0 {
vals[idx..end].reverse();
}
idx = end;
group += 1;
}
// Rebuild linked list
let mut dummy = Box::new(ListNode::new(0));
let mut cur = &mut dummy;
for &v in &vals {
cur.next = Some(Box::new(ListNode::new(v)));
cur = cur.next.as_mut().unwrap();
}
dummy.next
}
}