Menu
CoddyTech

Merge Two Sorted Lists

You get two singly linked lists, each stored in two arrays of the same length. In the first list, node i holds the value values1[i] and links to node next1[i]. The second list works the same way with next2 and values2. In both lists -1 ends the list and the head is node 0. The nodes are not stored in list order, so follow the links.

Each list is sorted in non-decreasing order along its links. Merge the two into one sorted list and return its values in order.

Function

mergeTwoLists(next1: integer-array, values1: integer-array, next2: integer-array, values2: integer-array) → integer-array
next1integer-array
the index of the node each node of the first list links to, or -1 for its last node
values1integer-array
the value held by each node of the first list
next2integer-array
the index of the node each node of the second list links to, or -1 for its last node
values2integer-array
the value held by each node of the second list
Returnsinteger-array
the values of the merged list, in order

Constraints

  • 1 ≤ L1 ≤ 2000, where L1 is the length of next1 and of values1.
  • 1 ≤ L2 ≤ 2000, where L2 is the length of next2 and of values2.
  • -1000 ≤ values1[i], values2[j] ≤ 1000
  • Each entry of next1 is -1 or a node index of the first list, and each entry of next2 is -1 or a node index of the second list.
  • Starting at node 0, each list visits every one of its nodes exactly once and then reaches -1. There is no cycle.
  • Along its links, each list is sorted in non-decreasing order.

Examples

Input
next1 = [2, -1, 1]values1 = [1, 6, 4]next2 = [3, 2, -1, 1]values2 = [2, 7, 9, 3]
Output
[1, 2, 3, 4, 6, 7, 9]
Explanation
Following the links, the first list visits nodes 0, 2, 1 and reads 1, 4, 6; the second reads 2, 3, 7, 9. Taking the smaller front each time gives 1, 2, 3, 4, 6, 7, 9.
challenge icon

Follow-up

Can you merge k sorted lists in O(N log k) time, where N is the total number of nodes?

Reset code
def mergeTwoLists(next1, values1, next2, values2):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next1 = [2, -1, 1]
values1 = [1, 6, 4]
next2 = [3, 2, -1, 1]
values2 = [2, 7, 9, 3]

Expected Output

[1, 2, 3, 4, 6, 7, 9]