Code:
from collections import deque, Counter
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
new = []
# merge each list and keep track of original list
for i in range(len(nums)):
for j in nums[i]:
new.append((j, i))
# sort so each sliding window represents a range
new.sort()
d = deque()
c = Counter()
res = [-float('inf'), float('inf')]
# iterate over sliding windows that contain each list
for i in new:
d.append(i)
c[i[1]] += 1
while len(c) == len(nums):
res = min(res, [d[0][0], d[-1][0]], key = lambda x: x[1] - x[0])
a, b = d.popleft()
c[b] -= 1
if not c[b]: del c[b]
return res
Comment