Smallest range in “K” Lists

Pattern: K-way merge

hard

Keep one value from every list in a min heap and remember the largest of them. The range from the heap's top to that maximum covers every list. Pop the top, push the next value from its list, update the maximum, and repeat until a list runs out. The best range seen is the answer.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given k sorted lists, return the smallest range [lo, hi] that includes at least one value from every list. A range is smaller when hi - lo is smaller, or when it is equal and lo is smaller. The example above gives [20, 24].

The catalogue has no practice link; LeetCode's Smallest Range Covering Elements from K Lists is the same task with the same tie rule.

Think first

  • If you pick one value from each list, which range covers them?
  • To shrink that range, which value should change?
  • When can you stop?

Hints

    Brute force, and why it fails

    Try every pair of values as the ends and check each list: O(N² × k).

    The key insight

    Like a sliding window over the merged order: the heap gives the left end and a running maximum the right end, and each value enters the heap once.

    Dry run

    heap0 4 5
    max5
    best[0, 5]

    lists [4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]. Start with 4, 0, 5: range [0, 5].

    Step 1 of 4

    The plan

    heap = first value of each list; mx = max of them
    loop:
        (v, i, j) = pop
        if mx - v is smaller than the best width: best = [v, mx]
        if j + 1 == len(list i): return best
        push list[i][j + 1]; mx = max(mx, that value)
    

    Complexity

    Time
    O(N log k)
    Space
    O(k)

    Each value is pushed at most once into a heap of k items.

    Edge cases

    • One list: the range is its smallest value twice.
    • Lists that share a value: width 0.
    • Lists far apart: the range joins their ends.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] smallestRange(int[][] lists) {
            PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> Integer.compare(x[0], y[0]));   // {value, list, index}
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < lists.length; i++) {
                heap.add(new int[]{lists[i][0], i, 0});   // one value from every list
                max = Math.max(max, lists[i][0]);
            }
            int bestLo = 0, bestHi = Integer.MAX_VALUE;
            while (true) {
                int[] top = heap.poll();                  // the smallest of the chosen values
                if ((long) max - top[0] < (long) bestHi - bestLo) { bestLo = top[0]; bestHi = max; }
                int i = top[1], j = top[2] + 1;
                if (j == lists[i].length) break;          // that list has nothing bigger: no range can drop its value
                heap.add(new int[]{lists[i][j], i, j});
                max = Math.max(max, lists[i][j]);
            }
            return new int[]{bestLo, bestHi};
        }
    }

    C++

    class Solution {
    public:
        vector<int> smallestRange(vector<vector<int>>& lists) {
            typedef pair<int, pair<int, int>> Item;  // {value, {list, index}}
            priority_queue<Item, vector<Item>, greater<Item>> heap;
            int mx = INT_MIN;
            for (int i = 0; i < static_cast<int>(lists.size()); i++) {
                heap.push(make_pair(lists[i][0], make_pair(i, 0)));   // one value from every list
                mx = max(mx, lists[i][0]);
            }
            int bestLo = 0, bestHi = INT_MAX;
            while (true) {
                Item top = heap.top();                    // the smallest of the chosen values
                heap.pop();
                if (static_cast<long long>(mx) - top.first < static_cast<long long>(bestHi) - bestLo) { bestLo = top.first; bestHi = mx; }
                int i = top.second.first, j = top.second.second + 1;
                if (j == static_cast<int>(lists[i].size())) break;   // that list has nothing bigger
                heap.push(make_pair(lists[i][j], make_pair(i, j)));
                mx = max(mx, lists[i][j]);
            }
            return vector<int>{bestLo, bestHi};
        }
    };

    Python

    import heapq
    
    class Solution:
        def smallestRange(self, lists: list[list[int]]) -> list[int]:
            heap = [(l[0], i, 0) for i, l in enumerate(lists)]   # one value from every list
            heapq.heapify(heap)
            mx = max(l[0] for l in lists)
            best = None
            while True:
                v, i, j = heapq.heappop(heap)       # the smallest of the chosen values
                if best is None or mx - v < best[1] - best[0]:
                    best = [v, mx]
                if j + 1 == len(lists[i]):
                    return best                     # that list has nothing bigger: no range can drop its value
                heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
                mx = max(mx, lists[i][j + 1])

    Common mistakes

    • Stopping when any list runs out instead of the list of the popped value.
    • Moving the maximum instead of the minimum.

    Similar problems