LeetCode #632 — HARD

Smallest Range Covering Elements from K Lists

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

Example 1:

Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
Explanation: 
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Example 2:

Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]

Constraints:

  • nums.length == k
  • 1 <= k <= 3500
  • 1 <= nums[i].length <= 50
  • -105 <= nums[i][j] <= 105
  • nums[i] is sorted in non-decreasing order.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Hash Map · Greedy · Sliding Window

Example 1

[[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]

Example 2

[[1,2,3],[1,2,3],[1,2,3]]

Related Problems

  • Minimum Window Substring (minimum-window-substring)
Step 02

Core Insight

What unlocks the optimal approach

  • No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

class Solution {
    public int[] smallestRange(List<List<Integer>> nums) {
        // [value, row, indexInRow] ordered by smallest value.
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        int currentMax = Integer.MIN_VALUE;

        // Seed heap with the first value from each list.
        for (int row = 0; row < nums.size(); row++) {
            int value = nums.get(row).get(0);
            minHeap.offer(new int[] { value, row, 0 });
            currentMax = Math.max(currentMax, value);
        }

        int bestLeft = 0;
        int bestRight = Integer.MAX_VALUE;

        // Keep one active element from every list.
        while (minHeap.size() == nums.size()) {
            int[] top = minHeap.poll();
            int value = top[0], row = top[1], col = top[2];

            // Candidate range is [current min, current max].
            if (currentMax - value < bestRight - bestLeft ||
                (currentMax - value == bestRight - bestLeft && value < bestLeft)) {
                bestLeft = value;
                bestRight = currentMax;
            }

            // Cannot continue when one list is exhausted.
            if (col + 1 == nums.get(row).size()) {
                break;
            }

            int nextValue = nums.get(row).get(col + 1);
            minHeap.offer(new int[] { nextValue, row, col + 1 });
            currentMax = Math.max(currentMax, nextValue);
        }

        return new int[] { bestLeft, bestRight };
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × log n)
Space
O(n)

Approach Breakdown

FLATTEN + SORT WINDOW
O(T log T) time
O(T) space

Flatten every value as (number, listId), sort by number, then run a sliding window that covers all list IDs. Correct and easier to reason about, but sorting all T values dominates runtime and memory.

K-WAY MIN HEAP
O(T log k) time
O(k) space

Maintain exactly one active candidate per list in a min-heap, plus the current maximum across candidates. Each pop/push moves one pointer forward and costs O(log k). Across all T elements, total work is O(T log k).

Shortcut: Always advance the list that currently provides the minimum value. That is the only move that can shrink the active range while keeping all k lists covered.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.

Shrinking the window only once

Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.

Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.

Fix: Shrink in a `while` loop until the invariant is valid again.