[LeetCode] Smallest Range Covering Elements from K Lists

632. Smallest Range Covering Elements from K Lists

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
map<int, vector<int>> counter;
vector<int> res = {(int)-1e5, (int)1e5};
int k = nums.size();
for(int i = 0; i < k; i++) {
for(auto& num : nums[i]) {
counter[num].push_back(i);
}
}
unordered_map<int, int> mp;
int right;
for(auto l = begin(counter), r = begin(counter); r != end(counter);) {
while(r != end(counter) and k) {
for(auto& pos : r->second) {
if(++mp[pos] == 1) k--;
}
r++;
}

while(l != r and !k) {
int left = l->first, right = prev(r)->first;
if(right - left < res[1] - res[0])
res = {left, right};
for(auto& pos : l->second) {
if(--mp[pos] == 0) k++;
}
l++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/LeetCode/smallest-range-covering-elements-from-k-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.