Tutorialspoint
Problem
Solution
Submissions

Smallest Range Covering Elements

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the smallest range that includes at least one number from each of the k lists. You have k lists of sorted integers in non-decreasing order. Find the smallest range [a, b] such that a <= b and for each list, there is at least one number x such that a <= x <= b.

Example 1
  • Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
  • Output: [20,24]
  • Explanation:
    • We need to pick one element from each list: [4,10,15,24,26], [0,9,12,20], [5,18,22,30].
    • One possible combination is 20 (from list 2), 22 (from list 3), and 24 (from list 1).
    • The range [20,24] covers all three elements and has length 4, which is the smallest possible.
Example 2
  • Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
  • Output: [1,1]
  • Explanation:
    • We can pick 1 from each list.
    • The range [1,1] covers all elements and has length 0.
    • This is the smallest possible range.
Constraints
  • nums.length == k
  • 1 <= k <= 3500
  • 1 <= nums[i].length <= 50
  • -10^5 <= nums[i][j] <= 10^5
  • nums[i] is sorted in non-decreasing order
  • Time Complexity: O(n * log k) where n is total number of elements
  • Space Complexity: O(k)
HeapTCS (Tata Consultancy Services)Airbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a min-heap to keep track of the smallest element from each list
  • Keep track of the maximum element among current candidates
  • Initially, add the first element from each list to the heap
  • The current range is [min_element, max_element]
  • Remove the minimum element and add the next element from the same list
  • Update the range if the new range is smaller
  • Continue until one of the lists is exhausted

Steps to solve by this approach:

 Step 1: Create a min-heap to store elements with their values, list indices, and element indices
 Step 2: Initialize the heap with the first element from each of the k lists
 Step 3: Keep track of the maximum value among all current elements in the heap
 Step 4: The current range is [min_heap_top, max_value] - update the smallest range if this is better
 Step 5: Remove the minimum element from heap and add the next element from the same list (if available)
 Step 6: Update the maximum value if the newly added element is larger
 Step 7: Continue until we can't maintain elements from all k lists, then return the smallest range found

Submitted Code :