Kth Smallest Number in M Sorted Lists

Find the kth smallest value across m sorted arrays — pop k times from a min-heap of (value, listIdx, idxInList).

Medium
Time O(k log m) Space O(m)
LeetCode
5 min read
k-way-merge heaps

Problem#

Given m sorted arrays, return the kth smallest value across all elements (1-indexed).

Examples#

  • lists = [[1,5,8],[4,12],[7,8,10]], k = 58

Constraints#

  • 1 <= m, 1 <= k <= total elements.

Approach#

Push the head of every list into a min-heap as (value, listIdx, idxInList). Pop k times; after each pop, push the next element of that list if it exists.

Solution#

Kth Smallest in M Sorted Lists
int kthSmallest(vector<vector<int>>& lists, int k) {
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
for (int i = 0; i < (int)lists.size(); ++i)
if (!lists[i].empty()) pq.emplace(lists[i][0], i, 0);
while (--k > 0) {
auto [v, li, ii] = pq.top(); pq.pop();
if (ii + 1 < (int)lists[li].size())
pq.emplace(lists[li][ii + 1], li, ii + 1);
}
return get<0>(pq.top());
}

Editorial#

The heap maintains the “frontier” of unconsumed elements — one per list. The kth pop yields the kth smallest across all lists, because pop order respects the global sort. Tracking (listIdx, idxInList) lets us advance the right list after each pop.

Complexity#

  • Time: O(k log m).
  • Space: O(m).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.