You have k
lists of sorted integers. Find the smallest range that includes at least one number from each of the k
lists.
For example,
List 1: [4, 10, 13, 14]
List 2: [0, 9, 15, 18]
List 3: [5, 18, 22, 30]
The smallest range here would be [14, 18]
as it contains 14
from list 1
, 15
from list 2
, and 18
from list 3
.
MY approach is:
K
lists But the only issue I am facing is: Suppose for one list there is no more elements left than should I finish there or should I continue?
Very nice O(n log n) algorithm!
You can finish there because you will never find the better interval fulfilling the given condition "range that includes at least one number from each of the k lists".
Suppose you are leaving current minimum m
(the last element from some list) and instead you are removing something (not minimum) from another list. In that case the range can only grow (because minimum of the range is determined by m
). So there is no point in doing that and you can just stop your algorithm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With