πDay 4. Linked List Group Reverse π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given the head of a linked list, the task is to reverse every k nodes in the linked list. If the number of nodes is not a multiple of k, the left-out nodes at the end should be treated as a group and must also be reversed.
π Example Walkthrough:
Input:
head = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8, k = 4
Output:
4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> 5
Explanation:
The first 4 nodes (1, 2, 3, 4) are reversed to become 4, 3, 2, 1.
The next 4 nodes (5, 6, 7, 8) are reversed to become 8, 7, 6, 5.
Hence, the resultant linked list is 4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> 5.
Input:
head = 1 -> 2 -> 3 -> 4 -> 5, k = 3
Output:
3 -> 2 -> 1 -> 5 -> 4
Explanation:
The first 3 nodes (1, 2, 3) are reversed to become 3, 2, 1.
The last 2 nodes (4, 5) are reversed to become 5, 4.
Hence, the resultant linked list is 3 -> 2 -> 1 -> 5 -> 4.
Constraints:
1 <= size of linked list <= $10^5$
1 <= data of nodes <= $10^6$
$1 <= k <=$ size of linked list
π― My Approach:
Reverse Nodes in Groups of Size
k:Reverse the first
knodes of the list iteratively.Keep track of the current group's head and tail to link the groups appropriately.
Repeat the process until all nodes are traversed.
Handling Edge Cases:
If
k = 1, the list remains unchanged.If the number of remaining nodes is less than
k, treat them as a single group and reverse them.
Steps:
Start with the head of the linked list and reverse the first
knodes.Use three pointers (
prev,curr,next) to reverse the nodes within each group.Update the
nextpointer of the previous group's tail to point to the reversed group's head.Repeat the process until all nodes are processed.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the number of nodes in the linked list. Each node is visited exactly once during the reversal process.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for pointer manipulation.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
Code (Python)(Alternative)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated