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 - c, or when the two widths are equal and a < c.

Example 1
Input: nums = [[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]]
Output: [20, 24]
Explanation: 24 is in list 1, 20 in list 2 and 22 in list 3.
Example 2
Input: nums = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Output: [1, 1]
Explanation: 1 is in all three lists, so a range of width 0 covers them.
Solution

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 three lists of Example 1 on one number line. The first picks 4, 0 and 5 give the range [0, 5], width 5. The picks 24, 20 and 22 give the smallest range, [20, 24], width 4.

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 PriorityQueue, in java.util, is one: poll() removes the smallest item, by the order of the comparator it is given. Its add and poll each take about log k steps for k items.

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}, and the comparator (a, b) -> Integer.compare(a[0], b[0]) orders entries by their value only.

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, max, holds the largest pick. Picks only move right, so max never needs to go down: each time a new number enters the heap, max is raised to it if the number is bigger.

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, best. Replacing best only when a range is strictly narrower keeps the earlier one, which is the one the rule wants.

Java Solution

The method smallestRange works in these steps:

  1. First, create heap, a PriorityQueue<int[]> with the comparator (a, b) -> Integer.compare(a[0], b[0]), so the entry with the smallest value comes out first.
  2. A loop over the lists adds each list's first number as {value, list index, 0}, and keeps the largest of these first numbers in max.
  3. Set best to the range of the first picks: heap.peek()[0], the smallest value in the heap, and max.
  4. Then a loop walks until a list is used up. Each round polls the smallest entry into min. If max - min[0] is smaller than the width of best, best becomes [min[0], max].
  5. Look up the list that min came from, and the position after min in it, next. If next equals that list's size, the list is used up, so return best.
  6. Otherwise read that list's number at next into v, add it to the heap with its list index and position, and raise max to v if it is bigger.

The main method runs both examples, a single list, a one-number list next to a list with a negative number, and two lists where two ranges tie in width.

Java
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:

Output
[20, 24]
[1, 1]
[5, 5]
[1, 3]
[1, 2]

[20, 24] and [1, 1] match the two examples. With the single list [5, 7, 9], the first pick alone covers the only list, so the answer is [5, 5], of width 0.

The fourth line comes from [[-5, 1, 8], [3]]. The list [3] has one number, so every range must contain 3. The walk drops -5, reaches [1, 3], and stops as soon as 3 itself is the smallest pick.

Look at the last line, [1, 2]. In [[1, 5], [2, 6]], the walk meets [1, 2] first and [5, 6] later, both of width 1. The later one is not strictly narrower, so best keeps [1, 2], the one with the smaller start.

The line max = Math.max(max, v) is easy to leave out, since the heap seems to take care of everything. Without it, max stays at 5 from the first picks, and Example 1 prints [20, 5], a range that ends below its start.

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 add or poll on a heap of k entries takes O(log k) steps.
  • Space: O(k), because the heap holds one pick from each of the k lists, and best is only two numbers.

A heap with one entry per list is the same setup as merging k sorted lists into one; see Merge k Sorted Lists.