![]() |
VOOZH | about |
Given a singly linked list and two integers X and Y, the task is to left rotate the linked list by X in groups of Y nodes.
Examples:
Input: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100, X = 2, Y = 4
Output: 30 -> 40 -> 10 -> 20 -> 70 -> 80 -> 50 -> 60 -> 90 -> 100
Explanation: First group of nodes is 10->20->30->40.
After rotating by 2, it becomes 30->40->10->20.
Second group of nodes is 50->60->70->80.
After rotating by 2, it becomes 70->80->50->60.
Third group of nodes is 90->100.
After rotating by 2, it becomes 90->100.Input: 40 -> 60 -> 70 -> 80 -> 90 -> 100, X = 1, Y = 3
Output: 70 -> 40 -> 60 -> 100 -> 80 -> 90
Approach: The problem can be solved by using reversal algorithm for rotation based on the below observation:
Let A1 -> B1 -> A2 -> B2 ->.......-> AnBn represents the complete list where, AiBi represents a group of Y nodes, and Ai and Bi represents the separate parts of this group at the node of rotation i.e. Ai has X nodes and Bi has (Y - X) nodes.
For all Ai and Bi such that 1 ≤ i ≤ N
- Reverse A and B of size X and (Y-X) nodes to get ArBr, where Ar and Br are reverse of A and B respectively,
- Reverse ArBr of size Y to get BA.
Follow the image shown below for a better understanding
Follow the steps mentioned below to solve the problem:
Below is the implementation of the above approach:
Given list 10 20 30 40 50 60 70 80 90 100 Rotated Linked List 30 40 10 20 70 80 50 60 90 100
Time Complexity: O(N) where N is the length of the linked list
Auxiliary Space: O(1)