Smallest Range Covering Elements from K Lists
Find the narrowest range of numbers that holds at least one number from each of several sorted lists.
Given k lists of integers, each sorted from smallest to largest, find the smallest range [a, b] that contains at least one number from every list. A range [a, b] counts as smaller than [c, d] when b - a < d - ca < c
Example 1
Output: [20, 24]
Explanation: 24 is in list 1, 20 in list 2 and 22 in list 3.
Example 2
Output: [1, 1]
Explanation: 1 is in all three lists, so a range of width 0 covers them.
The Idea
Think of three bus lines, each with a timetable of departure minutes in order. You want the shortest stretch of time in which a bus of every line leaves. The lists in Example 1 can be read as such timetables: line 1 leaves at minutes 4, 10, 15, 24 and 26, line 2 at 0, 9, 12 and 20, and line 3 at 5, 18, 22 and 30.
Choose one number from each list, and the range runs from the smallest chosen number to the largest. Look at the picture below. It draws the three lists of Example 1 on one number line, one row per list.
The box labelled "first picks: [0, 5]" holds the first number of each list: 4, 0 and 5. Together they make the range [0, 5], of width 5. The box labelled "smallest range: [20, 24]" holds 24, 20 and 22, of width 4, and no choice is narrower.
How do we get from the first box to the second without trying every choice? Start from the first picks and ask which one should change. Each list is sorted, so a pick can only move right, to a bigger number.
Moving the largest pick, 5, only stretches the range. Moving the middle pick, 4, leaves the left end at 0, so the range cannot shrink. Only moving the smallest pick, 0, can bring the two ends closer. So 0 in list 2 gives way to 9, and the range becomes [4, 9].
Repeating that step, the ranges go [0, 5], [4, 9], [5, 10], [9, 18], [10, 18], [12, 18], [15, 20], [18, 24] and [20, 24]. Now the smallest pick is 20, the last number of list 2. It has nowhere to move, so the walk stops, and the narrowest range it met is [20, 24].
Is it safe to drop the smallest pick for good? When 0 is dropped, the other picks are already the smallest numbers of their lists from 0 upward. So [0, 5] is the narrowest range that starts at 0, and nothing is lost by moving on.
So the whole search is one walk: keep one pick per list, always raise the smallest pick, and remember the narrowest range seen along the way.
Solution Approach
Turning the walk into code means settling three things, after a look at why trying every choice is slow: how to find the smallest pick quickly, how to know the largest pick, and when to stop and which range wins a tie.
Trying every choice
Why not simply try every way to pick one number per list? Example 1 has 5 × 4 × 4 = 80 ways, which is fine. But the count multiplies with every list: ten lists of 50 numbers each give 5010, about 1017 ways. The walk moves each pick past each number at most once, so its steps are at most the count of all the numbers.
Finding the smallest pick
Each step needs the smallest of the k current picks. A structure that always hands out its smallest item first is called a min-heap. Java's PriorityQueuejava.utilpoll()addpoll
What goes into the heap? A number alone is not enough: after polling it, the code must know which list it came from and where in that list it sits. So each entry is an array {value, list index, position}(a, b) -> Integer.compare(a[0], b[0])
Knowing the largest pick
The heap hands out only its smallest entry, so how do we know the right end of the range? A variable, maxmaxmax
Stopping and breaking ties
When does the walk end? When the smallest pick is the last number of its list, there is no bigger number to raise it to. Any range the walk has not met yet would still need a number from that list, and the walk has already tried the narrowest range for each of that list's numbers.
What about two ranges of the same width? The rule prefers the one with the smaller start. The smallest pick never goes down during the walk, so a range met earlier never starts later. The narrowest range so far is kept in a variable, bestbest
Java Solution
The method smallestRange
- First, create
, aheap with the comparatorPriorityQueue<int[]> , so the entry with the smallest value comes out first.(a, b) -> Integer.compare(a[0], b[0]) - A loop over the lists adds each list's first number as
, and keeps the largest of these first numbers in{value, list index, 0} .max - Set
to the range of the first picks:best , the smallest value in the heap, andheap.peek()[0] .max - Then a loop walks until a list is used up. Each round polls the smallest entry into
. Ifmin is smaller than the width ofmax - min[0] ,best becomesbest .[min[0], max] - Look up the list that
came from, and the position aftermin in it,min . Ifnext equals that list's size, the list is used up, so returnnext .best - Otherwise read that list's number at
intonext , add it to the heap with its list index and position, and raisev tomax if it is bigger.v
The main
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class SmallestRangeFromKLists {
public static int[] smallestRange(List<List<Integer>> nums) {
// entries are {value, list index, position in that list}; smallest value on top
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
int v = nums.get(i).get(0);
heap.add(new int[] {v, i, 0});
max = Math.max(max, v);
}
int[] best = {heap.peek()[0], max};
while (true) {
int[] min = heap.poll(); // the range is [min, max]
if (max - min[0] < best[1] - best[0]) {
best = new int[] {min[0], max}; // strictly narrower: a new best
}
List<Integer> list = nums.get(min[1]);
int next = min[2] + 1;
if (next == list.size()) {
return best; // this list has no bigger value left
}
int v = list.get(next);
heap.add(new int[] {v, min[1], next}); // raise the smallest pick
max = Math.max(max, v);
}
}
public static void main(String[] args) {
System.out.println(Arrays.toString(smallestRange(List.of(
List.of(4, 10, 15, 24, 26), List.of(0, 9, 12, 20), List.of(5, 18, 22, 30)))));
System.out.println(Arrays.toString(smallestRange(List.of(
List.of(1, 2, 3), List.of(1, 2, 3), List.of(1, 2, 3)))));
System.out.println(Arrays.toString(smallestRange(List.of(List.of(5, 7, 9)))));
System.out.println(Arrays.toString(smallestRange(List.of(
List.of(-5, 1, 8), List.of(3)))));
System.out.println(Arrays.toString(smallestRange(List.of(
List.of(1, 5), List.of(2, 6)))));
}
}
Running it prints:
[20, 24]
[1, 1]
[5, 5]
[1, 3]
[1, 2]
[20, 24][1, 1][5, 7, 9][5, 5]
The fourth line comes from [[-5, 1, 8], [3]][3][1, 3]
Look at the last line, [1, 2][[1, 5], [2, 6]][1, 2][5, 6]best[1, 2]
The line max = Math.max(max, v)max[20, 5]
Complexity
Each step of the walk polls one entry and adds one, and no number enters the heap twice.
- Time: O(N log k), because each of the N numbers in all the lists enters the heap at most once, and each
oradd on a heap of k entries takes O(log k) steps.poll - Space: O(k), because the heap holds one pick from each of the k lists, and
is only two numbers.best
A heap with one entry per list is the same setup as merging k sorted lists into one; see