Menu
CoddyTech

Sort List

You get a singly linked list stored in two arrays of the same length. Node i holds the value values[i] and links to node next[i], -1 ends the list, and the head is node 0. The nodes are not stored in list order, and the arrays may also hold leftover nodes that the walk from node 0 never reaches. Those are not part of the list, even when their links point into it.

Sort the list in non-decreasing order of value and return the values of its nodes in that order.

Function

sortList(next: integer-array, values: integer-array) → 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
Returnsinteger-array
the values of the list's nodes, smallest first

Constraints

  • 1 ≤ n ≤ 4000, where n is the length of next and of values.
  • -1000 ≤ values[i] ≤ 1000
  • Each next[i] is -1 or a node index from 0 to n-1.
  • Starting at node 0, the list reaches -1 without visiting a node twice.
  • Nodes the walk from node 0 does not reach are not part of the list. Their next entries may point anywhere.

Examples

Input
next = [3, -1, 4, 2, 1]values = [4, 1, 3, 2, 5]
Output
[1, 2, 3, 4, 5]
Explanation
The walk from node 0 visits nodes 0, 3, 2, 4, 1, so the list reads 4, 2, 3, 5, 1. Sorted, that is 1, 2, 3, 4, 5.
challenge icon

Follow-up

Can you sort by relinking the nodes in O(n log n) time, without copying the values out?

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

Test #1

Test #2

Test #3

Arguments

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

Expected Output

[1, 2, 3, 4, 5]