Merge Sorted Shelves

Medium · Heaps & Top-K · about 25 min

A library has k shelves. Each shelf is a list of book numbers sorted from smallest to largest. For the yearly stock check, the librarian needs one list of every book number, sorted from smallest to largest.

Return that list. Keep duplicates. Some shelves may be empty, and there may be no shelves at all.

Use a heap of the front book of each shelf, so the work is O(n log k) for n books in total.

Example: merge_shelves([[1, 4, 5], [1, 3, 4], [2, 6]]) → [1, 1, 2, 3, 4, 4, 5, 6]

Hints

  • The smallest book left is always at the front of one of the shelves.
  • Keep the front book of each non-empty shelf in a min-heap, and remember which shelf it came from.
  • After popping a book, push the next book from that same shelf, if it has one.

Learn the pattern first: the Heaps & Top-K lesson.

More Heaps & Top-K problems