Smallest Range Covering Elements from K Lists - Problem

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.

Return the smallest range as an array [start, end].

Input & Output

Example 1 — Basic Case
$ Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
💡 Note: The range [20,24] covers list 1 (24), list 2 (20), and list 3 (22). This gives the minimum range of 4.
Example 2 — Minimum Size
$ Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]
💡 Note: All lists contain 1, so the optimal range is [1,1] with range 0.
Example 3 — Different Ranges
$ Input: nums = [[10,20],[15,25],[5,30]]
Output: [15,20]
💡 Note: Range [15,20] covers 20 from list 1, 15 from list 2, and no direct element from list 3, but we need at least one from each. Actually [15,20] covers list 2 (15) and list 1 (20), but we need list 3. The correct answer would be [15,25] covering 20 from list 1, 15 from list 2, and 25 from list 3.

Constraints

  • nums.length == k
  • 1 ≤ k ≤ 3500
  • 1 ≤ nums[i].length ≤ 50
  • -105 ≤ nums[i][j] ≤ 105
  • nums[i] is sorted in non-decreasing order

Visualization

Tap to expand
Smallest Range Covering Elements from K Lists INPUT List 0: 4 10 15 24 26 List 1: 0 9 12 20 List 2: 5 18 22 30 Number Line View 0 20 24 30 List 0 List 1 List 2 [20,24] ALGORITHM STEPS 1 Use Min-Heap Initialize heap with first element from each list 2 Track Max Value Keep track of maximum among current elements 3 Calculate Range Range = [min_heap_top, max] Update if smaller range 4 Pop and Push Pop min, push next from same list. Repeat. Min-Heap State (Final): 20 22 24 min=20, max=24 FINAL RESULT Smallest Range Found: [20, 24] Range size: 24 - 20 = 4 Verification: List 0: 24 in [20,24] OK List 1: 20 in [20,24] OK List 2: 22 in [20,24] OK Time Complexity: O(n * log k) Space Complexity: O(k) Key Insight: The min-heap always gives us the smallest current element. By tracking the maximum separately, we can compute the range [heap_min, current_max]. Moving the minimum pointer forward explores all possible valid ranges efficiently. The process stops when any list is exhausted. TutorialsPoint - Smallest Range Covering Elements from K Lists | Optimal Solution (Min-Heap)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.2K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen