Merge k Sorted Lists
hardLinked List+40 XPTime limit 2s
Merge k sorted linked lists into one sorted list.
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:
- line 1:
k - then
klists, each in list format (2 lines)
Output: the merged list.
Constraints: 0 ≤ k ≤ 10⁴, total number of nodes ≤ 10⁵, −10⁴ ≤ value ≤ 10⁴.
Think about it: merging lists one by one costs O(k·N). Use a min-heap holding the current head of every list (O(N log k)), or merge them in pairs like merge sort.
Sample input 1
3 3 1 4 5 3 1 3 4 2 2 6
Sample output 1
1 1 2 3 4 4 5 6
Sample input 2
0
Sample output 2
empty
📖 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).