Given a linked list, the task is to reverse the nodes in groups of size k (where k is provided as input). If the total number of nodes is not a multiple of k, the remaining nodes at the end should be treated as a smaller group and reversed as well.
Example 1
Input: Linked List: 10 -> 20 -> 30 -> 40 -> 50, k = 2
Output: 20 -> 10 -> 40 -> 30 -> 50
Explanation: The first 2 elements 10, 20 are reversed to 20, 10. these are reversed first. The last element 50 remains as is since the group size is less than k.
Example 2
Input: Linked List: 5 -> 15 -> 25 -> 35 -> 45, k = 1
Output: 5 -> 15 -> 25 -> 35 -> 45
Explanation: Since k = 1, each group has only one node, so no changes are made. Resultant linked list: 5 -> 15 -> 25 -> 35 -> 45.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
10 20 30 40 50 2
20 10 40 30 50
5 15 25 35 45 1
5 15 25 35 45