#25

Reverse Nodes in k-Group

Hard
Linked ListRecursionLinked ListTwo PointersRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Iterative)
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses an iterative approach to reverse the nodes in groups of k without using extra space. This method efficiently links the reversed groups together while maintaining the overall structure of the list.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the total number of nodes in the linked list.
  2. 2Step 2: Use a loop to reverse nodes in groups of k until there are fewer than k nodes left.
  3. 3Step 3: For each group, reverse the nodes and link them back to the previous and next groups.
solution.py37 lines
1# Full working Python code with comments
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7class Solution:
8    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
9        # Count the number of nodes in the linked list
10        count = 0
11        current = head
12        while current:
13            count += 1
14            current = current.next
15
16        # Dummy node to help with the head of the new list
17        dummy = ListNode(0)
18        dummy.next = head
19        prev_group_end = dummy
20
21        # Reverse nodes in k-group
22        while count >= k:
23            current = prev_group_end.next
24            next_group_start = current
25            prev = None
26            for _ in range(k):
27                next_node = current.next
28                current.next = prev
29                prev = current
30                current = next_node
31            # Connect the end of the previous group to the start of the new group
32            prev_group_end.next = prev
33            next_group_start.next = current
34            prev_group_end = next_group_start
35            count -= k
36
37        return dummy.next

Complexity note: The time complexity is O(n) because we traverse the list a constant number of times (once to count nodes and once to reverse). The space complexity is O(1) since we are not using any extra space that grows with input size.

  • 1Reversing a linked list in groups requires careful management of pointers to maintain the structure of the list.
  • 2Understanding how to manipulate pointers in linked lists is crucial for solving problems involving node rearrangement.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.