398. Reverse Linked List in K-Groups (Reverse Remaining Too)

HardLinked ListLinked ListRecursion

Given a linked list, reverse the nodes k at a time. Unlike the standard variant, a final group of fewer than k nodes is also reversed. 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: Last group [5] reversed is itself.
Example 2
Input: [1,2,3,4,5], 3
Output: [3,2,1,5,4]
Explanation: Final partial group [4,5] also reversed.
Example 3
Input: [1,2,3,4,5,6,7], 3
Output: [3,2,1,6,5,4,7]
Explanation: Remaining [7] reversed.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →