![]() |
VOOZH | about |
Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ≤ i < N).
Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is.
Examples:
Input: head = 1->2->3->4->5->6->7->8->9, arr[] = {2, 3, 3}
Output: 2->1->5->4->3->8->7->6->9
Explanation: The first group of size 2 is 1->2. Upon reversing it becomes 2->1.
The next group of size 3 is 3->4->5 which on reversing becomes 5->4->3.
The last group of size 3 is 6->7->8 which on reversing becomes 8->7->6.Input: head = 6->8->7, arr[] = {1, 2}
Output: 6->7->8
Approach: The solution to the problem is based on the idea of selecting groups of nodes of arr[i] size and considering each sublist as an individual linked list and using the concept of reversing a linked list.
Follow the illustration below for a better understanding:
Illustration:
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach.
2->1->5->4->3->8->7->6->9->
Time Complexity: O(N)
Auxiliary Space: O(1)