Skip to content

Commit c0ba3cc

Browse files
authored
Merge pull request #787 from aaradhyasinghgaur/adding-LC-solution
Adding lc solution soluton for 25
2 parents 91984e7 + a04ba13 commit c0ba3cc

File tree

1 file changed

+141
-0
lines changed

1 file changed

+141
-0
lines changed
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
---
2+
id: remove-duplicates-from-sorted-list-2
3+
title: Reverse Nodes in k-Group (Leetcode)
4+
sidebar_label: 0025-ReverseNodesInK-Group
5+
description: 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.
6+
---
7+
8+
## Problem Description
9+
10+
| Problem Statement | Solution Link | LeetCode Profile |
11+
| :---------------- | :------------ | :--------------- |
12+
| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/) | [Reverse Nodes in k-Group Solution on LeetCode](https://leetcode.com/problems/reverse-nodes-in-k-group/solutions/) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) |
13+
14+
15+
## Problem Description
16+
17+
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
18+
19+
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.
20+
21+
You may not alter the values in the list's nodes, only nodes themselves may be changed.
22+
23+
### Examples
24+
25+
#### Example 1
26+
27+
- **Input:** $head = [1,2,3,4,5], k = 2$
28+
- **Output:** $[2,1,4,3,5]$
29+
30+
31+
#### Example 2
32+
33+
- **Input:** $head = [1,2,3,4,5], k = 3$
34+
- **Output:** $[3,2,1,4,5]$
35+
36+
37+
38+
### Constraints
39+
40+
- The number of nodes in the list is $n$.
41+
- $1 <= k <= n <= 5000$
42+
- $0 <= Node.val <= 1000$
43+
44+
45+
46+
### Intuition
47+
48+
The code aims to reverse nodes in a linked list in groups of $k$. It first checks if the length of the list is less than $k$ ; if so, it returns the head as-is. If the head is null or the list has only one node, or $k$ is less than 2, it returns the head. The core logic involves reversing the first $k$ nodes using a loop and recursively calling the function on the remaining nodes. The reversed portion is then linked with the result of the recursive call, ensuring the entire list is processed in $k$-sized groups.
49+
50+
51+
### Approach
52+
53+
1. **Calculate Length of the Linked List:**
54+
55+
- Implement a helper function Length to calculate and return the size of the linked list. This function iterates through the list, incrementing a counter until the end of the list is reached.
56+
57+
2. **Initial Checks:**
58+
59+
- In the reverseKGroup function, first check if $k$ is greater than the length of the list using the Length function. If so, return the head as is since there are not enough nodes to form a group.
60+
- Check if the head is null, the list has only one node, or if $k$ is less than 2. If any of these conditions are true, return the head as-is since no reversal is needed.
61+
62+
3. **Reverse First k Nodes:**
63+
64+
- Initialize three pointers: prev as null, curr as head, and next as null.
65+
- Use a loop to reverse the first $k$ nodes. Within the loop:
66+
- Store the next node of curr in next.
67+
Reverse the link by setting curr->next to prev.
68+
- Move the prev pointer to curr and curr to next.
69+
- Increment the count to ensure only $k$ nodes are processed.
70+
71+
3. **Recursive Call:**
72+
73+
- After reversing the first $k$ nodes, if next is not null (indicating there are more nodes left to process), make a recursive call to reverseKGroup with curr (the node following the first $k$ nodes) and $k$.
74+
- Link the last node of the reversed group (which is now the head) to the result of the recursive call.
75+
76+
4. **Return New Head:**
77+
78+
- Return prev as the new head of the reversed portion of the list.
79+
80+
### Solution Code
81+
82+
83+
#### C++
84+
85+
```cpp
86+
#include <iostream>
87+
88+
// Definition for singly-linked list.
89+
struct ListNode {
90+
int val;
91+
ListNode *next;
92+
ListNode() : val(0), next(nullptr) {}
93+
ListNode(int x) : val(x), next(nullptr) {}
94+
ListNode(int x, ListNode *next) : val(x), next(next) {}
95+
};
96+
97+
int Length(ListNode *head) {
98+
int size = 0;
99+
ListNode *temp = head;
100+
while (temp != nullptr) {
101+
temp = temp->next;
102+
size++;
103+
}
104+
return size;
105+
}
106+
107+
class Solution {
108+
public:
109+
ListNode* reverseKGroup(ListNode* head, int k) {
110+
if (k > Length(head)) {
111+
return head;
112+
}
113+
if (head == nullptr || head->next == nullptr || k < 2) {
114+
return head;
115+
}
116+
117+
int count = 0;
118+
ListNode *prev = nullptr;
119+
ListNode *curr = head;
120+
ListNode *next = nullptr;
121+
122+
while (count < k) {
123+
next = curr->next;
124+
curr->next = prev;
125+
prev = curr;
126+
curr = next;
127+
count++;
128+
}
129+
130+
if (next != nullptr) {
131+
head->next = reverseKGroup(curr, k);
132+
}
133+
134+
return prev;
135+
}
136+
};
137+
```
138+
139+
### Conclusion
140+
141+
The provided code effectively reverses nodes in a linked list in groups of $k$. It first calculates the length of the linked list to ensure there are enough nodes to form a group. If the length is less than $k$, it returns the head as is. The code then uses a loop to reverse the first $k$ nodes and recursively processes the remaining nodes, ensuring the entire linked list is processed in groups of $k$ while maintaining the order and structure of the reversed segments. The time complexity of this approach is $O(n)$, where $n$ is the number of nodes in the linked list, as each node is processed exactly once. The space complexity is $O(n/k)$ due to the recursion stack, as in the worst case, the depth of the recursion stack can be $n/k$, where $n$ is the total number of nodes and $k$ is the group size.

0 commit comments

Comments
 (0)