You are given the head of a singly linked list and an integer k. Your task is to reverse the nodes of the linked list in groups of size k and return the head of the modified list. If the remaining nodes are fewer than k, leave them unchanged.
Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: The nodes are reversed in groups of 2, while the last node remains unchanged.
Example 2
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Explanation: The first group of 3 nodes is reversed, and the remaining nodes are left unchanged.
Example 3
Input: head = [1,2,3,4,5,6], k = 3
Output: [3,2,1,6,5,4]
Explanation: Each group of 3 nodes is reversed.
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.
1 2 3 4 5 2
2 1 4 3 5
1 2 3 4 5 3
3 2 1 4 5