Practice › Heap & Priority Queue
Smallest Range Covering K Lists
Hard · Heap & Priority Queue · Asked at Google, Amazon, Microsoft, Uber
You have k lists, each sorted in non-decreasing order. Find the smallest range [a, b] that contains at least one number from every list, and print a b.
Range [a, b] is smaller than [c, d] if b − a < d − c, or if b − a = d − c and a < c.
Input
First line: k. Then, for each list, a line with its length m and a line with its m values.
Output
Two integers a b.
Constraints
- 1 ≤ k ≤ 3500
- 1 ≤ m ≤ 50
- −10^5 ≤ values ≤ 10^5
Keep one pointer per list and a min-heap of the current values, plus the current maximum. The range is [heap top, maximum]. Advance the list that holds the minimum; stop when that list runs out.
Example 1
Input
3 5 4 10 15 24 26 4 0 9 12 20 4 5 18 22 30
Output
20 24
Example 2
Input
3 3 1 2 3 3 1 2 3 3 1 2 3
Output
1 1
Hints
- Pick one number from each list. The range they span is [their minimum, their maximum].
- To make that range smaller you must raise the minimum — move forward in the list that holds it.
- A min-heap gives the minimum; track the maximum separately.
Approach
Start with the first element of every list in a min-heap and the largest of them as max. Each step, the current range is [heap top, max]; keep it if it beats the best (shorter, or same length with smaller start). Then replace the top with the next element of its list and update max. When the list that holds the minimum is exhausted, no range covering all lists can have a larger minimum, so stop.
Complexity: O(N log k) time for N numbers in total · O(k) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k;
cin >> k;
vector<vector<long long>> lists(k);
for (auto &l : lists) {
int m;
cin >> m;
l.resize(m);
for (auto &x : l) cin >> x;
}
priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
long long mx = LLONG_MIN;
for (int i = 0; i < k; i++) {
pq.push({lists[i][0], i, 0});
mx = max(mx, lists[i][0]);
}
long long bestA = get<0>(pq.top()), bestB = mx;
while (true) {
auto _b = pq.top();
auto v = get<0>(_b);
auto i = get<1>(_b);
auto j = get<2>(_b);
pq.pop();
if (mx - v < bestB - bestA || (mx - v == bestB - bestA && v < bestA)) {
bestA = v;
bestB = mx;
}
if (j + 1 == (int) lists[i].size()) break;
long long nv = lists[i][j + 1];
pq.push({nv, i, j + 1});
mx = max(mx, nv);
}
cout << bestA << " " << bestB << "\n";
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
k, p = data[0], 1
lists = []
for _ in range(k):
m = data[p]
lists.append(data[p + 1 : p + 1 + m])
p += 1 + m
heap = [(l[0], i, 0) for i, l in enumerate(lists)]
heapq.heapify(heap)
mx = max(l[0] for l in lists)
best = (heap[0][0], mx)
while True:
v, i, j = heapq.heappop(heap)
if mx - v < best[1] - best[0] or (mx - v == best[1] - best[0] and v < best[0]):
best = (v, mx)
if j + 1 == len(lists[i]):
break
nv = lists[i][j + 1]
heapq.heappush(heap, (nv, i, j + 1))
mx = max(mx, nv)
print(best[0], best[1])Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int k = (int) in.nval;
long[][] lists = new long[k][];
for (int i = 0; i < k; i++) {
in.nextToken();
int m = (int) in.nval;
lists[i] = new long[m];
for (int j = 0; j < m; j++) {
in.nextToken();
lists[i][j] = (long) in.nval;
}
}
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
long mx = Long.MIN_VALUE;
for (int i = 0; i < k; i++) {
pq.add(new long[] {lists[i][0], i, 0});
mx = Math.max(mx, lists[i][0]);
}
long bestA = pq.peek()[0], bestB = mx;
while (true) {
long[] t = pq.poll();
long v = t[0];
int i = (int) t[1], j = (int) t[2];
if (mx - v < bestB - bestA || (mx - v == bestB - bestA && v < bestA)) {
bestA = v;
bestB = mx;
}
if (j + 1 == lists[i].length) break;
long nv = lists[i][j + 1];
pq.add(new long[] {nv, i, j + 1});
mx = Math.max(mx, nv);
}
System.out.println(bestA + " " + bestB);
}
}Solve Smallest Range Covering K Lists online · All practice problems