Problem solution · Python

Smallest Range Covering Elements from K Lists

Smallest Range Covering Elements from K Lists: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
20 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Smallest Range Covering Elements from K Lists, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 20 lines of Python from the credited upstream file 632.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSmallest Range Covering Elements from K Lists · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def smallestRange(self, nums: list[list[int]]) -> list[int]:    minHeap = [(row[0], i, 0) for i, row in enumerate(nums)]    heapq.heapify(minHeap)     maxRange = max(row[0] for row in nums)    minRange = heapq.nsmallest(1, minHeap)[0][0]    ans = [minRange, maxRange]     while len(minHeap) == len(nums):      num, r, c = heapq.heappop(minHeap)      if c + 1 < len(nums[r]):        heapq.heappush(minHeap, (nums[r][c + 1], r, c + 1))        maxRange = max(maxRange, nums[r][c + 1])        minRange = heapq.nsmallest(1, minHeap)[0][0]        if maxRange - minRange < ans[1] - ans[0]:          ans[0], ans[1] = minRange, maxRange     return ans 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗