Skip to content
Preptima
mediumCodingConceptMidSeniorStaff

You are handed k sorted lists and asked for one sorted list. What is wrong with concatenating and sorting?

Nothing about correctness - it works. It throws away the sortedness you were given and pays O of N log N to rebuild it, where merging costs O of N log k, and it requires every element resident at once where a merge requires k. On lists that arrive as streams the second objection is the one that disqualifies it outright.

6 min readUpdated 2026-08-15

Answer

Short answer

Merge k sorted lists with a min-heap that holds the current head of each non-empty list. Repeatedly pop the smallest value, append it, and push the next value from the same source list. This uses O(k) extra memory and O(N log k) time, preserving the sorted order already present in the inputs.

Was this answer helpful?

Likely follow-ups

  • The lists are files far larger than memory and the output is a file too. Which part of your answer survives unchanged?
  • Merge them in place across the input arrays with no output buffer. What does that cost you?
  • One of the k lists is nine tenths of the data. Does anything about your bound or your constants change?
  • Each list is sorted by a key you must compute rather than read. Where do you put that computation?

Related questions

Further reading