leetcode 632 Smallest Range
You have K lists of sorted integers. Write a function that finds the smallest range that encompasses at least one number from each of the K lists.
This is a popular software engineering interview problem, given by companies such as Google, Amazon, and Facebook. In this episode, we’ll develop a strategy to solve it and then we’ll step through the source code of an actual implementation, written in Java.
To put some context for this problem, think of several of your favorite music bands that tour the country. Every now and then they perform in the same city, which of course would be Los Angeles, and the dates of their performances are known in advance. Now, you’d like to schedule your visit to Los Angeles with the goal of seeing at least one performance by each of the bands. But with all the mad traffic, you don’t want to stay there for longer than you have to. So your task is to minimize the date range of being there while still seeing each of the bands.
A particularly graceful solution to this problem is to use a priority queue that stores just 1 value from each list. Then when taking a value out from the queue, you put in the next value from the same list. So if you have k lists, there will be at most k numbers in the queue at any given time.
We can keep track of the maximum number in the queue in a temporary variable and keep updating it as new values are put in. Since this is a priority queue, when we remove an element, it’ll automatically be the smallest value in the queue. So we can readily check the boundary range between the min and max values as we repeatedly remove and add new values into the queue.
Source code of an implementation written in Java:
https://bitbucket.org/StableSort/play...
The algorithm runs in O(k log k) + O(n log k)
Written and narrated by Andre Violentyev