406. Reverse a Linked List in Alternate Groups

HardLinked ListLinked ListPointers

Given a linked list and an integer k, leave the first k nodes as-is, reverse the next k nodes, leave the next k as-is, and so on alternately (the first group is kept, the second reversed, etc.). A final partial group follows the same alternating rule. 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,6,7,8,9], 3
Output: [1,2,3,6,5,4,7,8,9]
Explanation: Keep, reverse, keep.
Example 2
Input: [1,2,3,4,5], 2
Output: [1,2,4,3,5]
Explanation: Keep first pair, reverse next pair.
Example 3
Input: [1], 1
Output: [1]
Explanation: Single node kept.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →