> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Reverse Nodes in k-Group Python Solution

> Tested Python solution for LeetCode 25 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 25, Hard. Topics: Linked List, Recursion. [View on LeetCode](https://leetcode.com/problems/reverse-nodes-in-k-group/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 25   # by problem number
lcpy gen -s reverse_nodes_in_k_group   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg)

```
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
```

![Example 2](https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg)

```
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
```

### Constraints

* The number of nodes in the list is n.
* 1 \<= k \<= n \<= 5000
* 0 \<= Node.val \<= 1000

**Follow-up:** Can you solve the problem in `O(1)` extra memory space?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reverse_nodes_in_k_group/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reverse_nodes_in_k_group/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(n)
    # Space: O(1)
    def reverse_k_group(self, head: ListNode[int] | None, k: int) -> ListNode[int] | None:
        if not head or k == 1:
            return head

        # Check if we have at least k nodes
        curr: ListNode[int] | None = head
        count = 0
        while curr and count < k:
            curr = curr.next
            count += 1

        if count == k:
            # Reverse the first k nodes
            prev = self.reverse_k_group(curr, k)  # Recursively reverse remaining groups
            curr = head

            while count > 0 and curr is not None:
                next_temp = curr.next
                curr.next = prev
                prev = curr
                curr = next_temp
                count -= 1

            head = prev

        return head
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
