#632

Smallest Range Covering Elements from K Lists

Hard
ArrayHash TableGreedySliding WindowSortingHeap (Priority Queue)HeapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(1)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

The optimal solution uses a min-heap to efficiently track the smallest elements from each list while maintaining the largest element seen so far. This allows us to dynamically adjust the range as we iterate through the lists.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a min-heap and add the first element of each list along with its list index.
  2. 2Step 2: Track the maximum value from the elements in the heap.
  3. 3Step 3: Continuously extract the minimum element from the heap, calculate the current range, and update the best range if the current range is smaller.
  4. 4Step 4: If the extracted element has a next element in its list, push that next element into the heap and update the maximum value if necessary.
  5. 5Step 5: Repeat until we can no longer extract elements from the heap.
solution.py22 lines
1# Full working Python code
2import heapq
3
4def smallestRange(nums):
5    min_heap = []
6    current_max = float('-inf')
7    for i in range(len(nums)):
8        heapq.heappush(min_heap, (nums[i][0], i, 0))
9        current_max = max(current_max, nums[i][0])
10    best_range = [float('-inf'), float('inf')]
11
12    while min_heap:
13        current_min, list_index, element_index = heapq.heappop(min_heap)
14        if current_max - current_min < best_range[1] - best_range[0]:
15            best_range = [current_min, current_max]
16        if element_index + 1 < len(nums[list_index]):
17            next_element = nums[list_index][element_index + 1]
18            heapq.heappush(min_heap, (next_element, list_index, element_index + 1))
19            current_max = max(current_max, next_element)
20        else:
21            break
22    return best_range

Complexity note: The time complexity is O(n log k) because we are using a min-heap to manage the elements from k lists, where n is the total number of elements and k is the number of lists.

  • 1Using a min-heap allows efficient tracking of the smallest element across multiple lists.
  • 2Maintaining the maximum element seen so far helps in calculating the range quickly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.