632 Smalllest Range Covering Elements from K Lists
Problem Statement
You have k
lists of sorted integers in non-decreasing order.
Instructions
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]
ifb - a < d - c
ora < c
ifb - a == d - c
.
For the whole problem statement, please refer here.
Plans
Find the smallest range that includes at least one number from each of the
k
lists of sorted integers.This approach will allow us to efficiently manage the current minimum and maximum values from the lists.
Track the next element to be considered from each list.
Continue to expand our range until all lists are represented.
Update the smallest range whenever a new valid range is found.
Solution
Explanation
Initialize
We start by creating a
min_heap
which will store tuples of the form(value, list_index, element_index)
. The value is the integer from the list, thelist_index
helps identify which list it came from, and theelement_index
indicates the position in that list.The variable
current_max
is used to keep track of the maximum number in the current range.
Populate the Heap
Initially, we populate the heap with the first element of each list. We also update
current_max
as we insert elements.
Finding the Smallest Range
Continously extract the minimum element from the healp. This gives us the smallest current element (
current_min
).At each step, we check if the range defined by
current_min
andcurrent_max
is the smallest we have found so far.If is is smallest, we update our
smallest_range
.
Push Next Elements
After removing the smallest element, if there is a next element in the same list, we push that next element into the heap and update
current_max
if the new value is larger.If we exhaust any list (no more elmements to pus), we stop the process as we can no longer form a valid range.
Return the Result
The method finally returns the smallest range that covers at least one element from each of the input lists.
Last updated