Smallest Range Covering Elements from K Lists

Smallest [lo, hi] covering at least one element from each of k sorted lists — k-way merge tracking running max.

Hard
Time O(N log k) Space O(k)
LeetCode
6 min read
top-k heaps k-way-merge

Problem#

Given k sorted lists of integers, find the smallest range [lo, hi] such that at least one number from each list lies in the range.

Examples#

  • nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]][20,24]

Constraints#

  • Sum of lengths up to 3500.

Approach#

Min-heap holds the current frontier (one element per list). Track the running max across the frontier. At each step the range is [heap.top, max]; pop the smallest and advance that list, updating max. Stop when any list is exhausted.

Solution#

Smallest Range Covering K Lists
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
int curMax = INT_MIN;
for (int i = 0; i < (int)nums.size(); ++i) {
pq.emplace(nums[i][0], i, 0);
curMax = max(curMax, nums[i][0]);
}
int rangeLo = -1e5, rangeHi = 1e5;
while (true) {
auto [v, li, ii] = pq.top(); pq.pop();
if (curMax - v < rangeHi - rangeLo) {
rangeLo = v;
rangeHi = curMax;
}
if (ii + 1 == (int)nums[li].size()) break;
int nxt = nums[li][ii + 1];
curMax = max(curMax, nxt);
pq.emplace(nxt, li, ii + 1);
}
return {rangeLo, rangeHi};
}
};

Editorial#

The min in the heap and curMax give the current covering range; the range is “valid” by construction (one per list). Advancing the min is the only move that could shrink the range — advancing any other element would only widen it. Stop when a list is exhausted because we’d lose the “one per list” coverage.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.