392. Reverse Alternate K Nodes

MediumLinked ListLinked ListRecursion

Given a linked list and an integer k, reverse the first k nodes, leave the next k nodes as they are, reverse the following k nodes, and so on alternately until the end. A final partial group follows the same alternating rule (reverse it if it falls on a reverse turn). 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: [3,2,1,4,5,6,9,8,7]
Explanation: Reverse, skip, reverse.
Example 2
Input: [1,2,3,4,5], 2
Output: [2,1,3,4,5]
Explanation: Reverse first pair, skip next pair.
Example 3
Input: [1], 1
Output: [1]
Explanation: Single node reversed (itself).

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →