1
input [[1,4,5],[1,3,4],[2,6]]
output [1,1,2,3,4,4,5,6]

I have done a baby way by putting each value in to one process list which takes 2 loops and another loop for sorting

Is there any way to do it within O(n) or as fast as possible or not with using any function

def sortmerge(inputList):
    processList = []
    sortedList= []
    for i in range(len(inputList)):
        for j in range(len(inputList[i])):
            processList.append(inputList[i][j])
    # processList.sort()
    while processList:
        minimum = processList[0] 
        for x in processList: 
            if x < minimum:
                minimum = x
        sortedList.append(minimum)
        processList.remove(minimum)
    return sortedList
khemmawhy
  • 9
  • 2

1 Answers1

0

According to your comment, the sub-lists might not be sorted. Therefore, O(n) is not possible since sorting is required, but you can get O(n log n) by flattening then sorting.

from itertools import chain

inputList = [[1, 4, 5], [1, 3, 4], [2, 6]]
print(sorted(chain.from_iterable(inputList)))  # -> [1, 1, 2, 3, 4, 4, 5, 6]

(sorted() uses TimSort, which is O(n log n), and chaining is O(n).)

There might be faster ways than this if you can make more guarantees about your input data. For example, if only a few sublists might be unsorted, it could be faster to sort them, then merge.

Due credit to deceze for posting this solution in a comment

wjandrea
  • 16,334
  • 5
  • 30
  • 53