Skills101
← All coding problems

Reverse Nodes in k-Group

hardLinked List+40 XPTime limit 2s

Reverse the nodes of the list k at a time. If the number of nodes left at the end is less than k, leave them as they are.

Example: 1 2 3 4 5 with k = 2 → 2 1 4 3 5; with k = 3 → 3 2 1 4 5.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: one list, then a third line k.

Output: the resulting list.

Constraints: 1 ≤ k ≤ n ≤ 10⁵.

Challenge: relink the nodes in place with O(1) extra memory. Before reversing a group, check that k nodes remain; keep a pointer to the node before the group so you can attach the reversed group.

Sample input 1

5
1 2 3 4 5
2

Sample output 1

2 1 4 3 5

Sample input 2

5
1 2 3 4 5
3

Sample output 2

3 2 1 4 5

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.