Menu
CoddyTech

Reverse Nodes in k-Group

A singly linked list is stored in two arrays of the same length. Node i holds values[i] and links to node next[i]; -1 ends the list, and the head is node 0. The nodes may be stored in any order, so follow the links, not the array order.

Reverse the list in groups of k nodes: the first k nodes come out reversed, then the next k, and so on. A last group of fewer than k nodes keeps its order. Return the values in the new list order.

Function

reverseKGroup(next: integer-array, values: integer-array, k: integer) → integer-array
nextinteger-array
the index of the node each node links to, or -1 for the last node
valuesinteger-array
the value held by each node
kinteger
the number of nodes in each group to reverse
Returnsinteger-array
the values in the new list order

Constraints

  • 1 ≤ L ≤ 5000, where L is the length of next and of values.
  • -1000 ≤ values[i] ≤ 1000
  • 1 ≤ k ≤ L
  • Each next[i] is -1 or a node index from 0 to L-1.
  • Starting at node 0, the list visits every node exactly once and then reaches -1. There is no cycle.

Examples

Input
next = [2, 3, 4, -1, 1]values = [1, 4, 2, 5, 3]k = 2
Output
[2, 1, 4, 3, 5]
Explanation
The list reads 1, 2, 3, 4, 5 (nodes 0, 2, 4, 1, 3). The pairs 1, 2 and 3, 4 are reversed, and 5 alone is shorter than k = 2, so it stays last.
challenge icon

Follow-up

Can you write it recursively, reversing one group and recursing on the rest of the list? How much extra memory does that use?

Reset code
def reverseKGroup(next, values, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next = [2, 3, 4, -1, 1]
values = [1, 4, 2, 5, 3]
k = 2

Expected Output

[2, 1, 4, 3, 5]