Skip to main content
Back to problems
#25
Hard Algorithms

Reverse nodes in k-group

Linked List Recursion
65.4% acceptance
Jan 12, 2026
15544
800
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
    if k <= 1 {
      return head;
    }
    
    // Check if we have at least k nodes
    let mut count = 0;
    let mut curr = &head;
    while let Some(node) = curr {
      count += 1;
      if count == k {
        break;
      }
      curr = &node.next;
    }
    
    // If we don't have k nodes, return as is
    if count < k {
      return head;
    }
    
    // Reverse first k nodes
    let mut prev = None;
    let mut curr = head;
    let mut count = 0;
    
    while count < k {
      if let Some(mut node) = curr {
        let next = node.next.take();
        node.next = prev;
        prev = Some(node);
        curr = next;
        count += 1;
      } else {
        break;
      }
    }
    
    // prev is now the new head of the reversed group
    // curr is the head of the remaining list
    // The original head is now the tail of the reversed group
    
    // Recursively reverse the rest and connect
    if let Some(mut new_head) = prev {
      // Find the tail of the reversed group (original head)
      let mut tail = &mut new_head;
      while tail.next.is_some() {
        tail = tail.next.as_mut().unwrap();
      }
      
      // Connect tail to the reversed remaining list
      tail.next = Self::reverse_k_group(curr, k);
      
      Some(new_head)
    } else {
      None
    }
  }
}