Linked Lists
65 / 170Linked ListsLesson 10 of 12About 49 min
Pair them up and merge in rounds. The complexity difference against the obvious approach is the lesson.
You can already merge two sorted lists. To merge k of them, the obvious move is to merge the first two, then merge that result with the third, and so on.
That is correct and slow. The accumulator grows by n nodes each round and is walked in full every time, so the total work is n, then 2n, then 3n, and so on up to k rounds. That sums to about n times k squared over two, which is O(n k squared).
Suppose you merge k sorted lists by repeatedly merging the running result with the next list. With k lists of n nodes each, what is the total time? Give space as the extra space beyond the output.
result = lists[0]for i in range(1, len(lists)): result = merge_two(result, lists[i])return resultRead the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.