25.reverse-nodes-in-k-groups-en
Problem
https://leetcode.com/problems/reverse-nodes-in-k-group/
Problem Description
Solution
Traverse linked list
from left to right, during traverse, group nodes in k, then reverse each group. How to reverse a linked list given start, end node?
Reverse linked list:
Initial a prev node
null
For each move, use temp node to keep current next node.
During traverse, update current node pointing to previous node, update previous pointing to current node
Update current to temp
For example(as below pic): reverse the whole linked list 1->2->3->4->null
-> 4->3->2->1->null
Here Reverse each group(k nodes
):
First group, use
count
keep track linked list counts when traverse linked listUse
start
to keep track each group start node position.Use
end
to keep track each group end node positionReverse(
k nodes
)AKA:(start, end) - start and end exclusively
.After reverse, update
start
point to reversed group last node.If
counts % k != 0
, thenend
move to next(end=end.next
), for each movecount+1
.
As below pic show steps 4 and 5, reverse linked list in range (start, end)
:
For example(as below pic),head=[1,2,3,4,5,6,7,8], k = 3
NOTE: Usually we create a
dummy node
to solve linked list problem, because head node may be changed during operation. for example: herehead updated from 1->3
, anddummy (List(0))
keep the same.
Complexity Analysis
Time Complexity:
O(n) - n is number of Linked List
Space Complexity:
O(1)
Key Points
create a dummy node,
dummy = ListNode(0)
Group linked list as
k=3
, keep track of start and end node for each group.Reverse each group, update start and end node references
return
dummy.next
.
Code (Java/Python3
)
Java/Python3
)Java Code
Python3 Cose
References
Extension
Require from right to left reverse nodes in k groups. (ByteDance Interview)
Example,
1->2->3->4->5->6->7->8, k = 3
,From right to left, group as
k=3
:6->7->8
reverse to8->7->6
,3->4->5
reverse to5->4->3
.1->2
only has 2 nodes, which less thank=3
, do nothing.return:
1->2->5->4->3->8->7->6
Here, we pre-process linked list, reverse it first, then using Reverse nodes in K groups solution:
Reverse linked list
From left to right, reverse linked list group as k nodes.
Reverse step #2 linked list
For example:1->2->3->4->5->6->7->8, k = 3
Reverse linked list:
8->7->6->5->4->3->2->1
Reverse nodes in k groups:
6->7->8->3->4->5->2->1
Reverse step#2 linked list:
1->2->5->4->3->8->7->6
Similar Problems
Last updated