356. Reverse Linked List in Groups of K

MediumLinked ListLinked ListRecursion

Given a linked list, reverse the nodes of the list k at a time and return the modified list. Nodes in a final group of fewer than k are left as-is. The list is given as an array; return the result as an array. Input: '[list], k'.

Input: '[list], k'.

Output: Array — the modified list.

Examples

Example 1
Input: [1,2,3,4,5], 2
Output: [2,1,4,3,5]
Explanation: Pairs reversed; last node stays.
Example 2
Input: [1,2,3,4,5], 3
Output: [3,2,1,4,5]
Explanation: First triple reversed.
Example 3
Input: [1], 1
Output: [1]
Explanation: Single node.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →