Skip to content
Problem 632 · LeetCode 632(opens in a new tab)

Smallest Range Covering Elements from K Lists

HardArrays

You are given k lists of whole numbers, each sorted from small to large. Find the smallest range [a, b] that contains at least one number from every list.

A range [a, b] is smaller than [c, d] when b − a < d − c, or when the widths are equal and a < c. Return the smallest range as [a, b].

Example 1

Input:  nums = [[1, 7, 12], [3, 9], [6, 10, 15]]
Output: [6, 9]
Why:    7, 9 and 6 all fall in [6, 9], width 3
2 more examples and the constraints

Example 2

Input:  nums = [[4, 5], [5, 8], [2, 5]]
Output: [5, 5]
Why:    every list contains a 5

Example 3

Input:  nums = [[2, 30]]
Output: [2, 2]
Why:    one list: any single number covers it

Constraints

  • 1 ≤ k ≤ 3,500
  • 1 ≤ length of each list ≤ 50
  • −100,000 ≤ every number ≤ 100,000
  • Each list is sorted in non-decreasing order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every startO(N·k·log m)
  2. Min-heap of list headsO(N log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 3,500 lists of 50Verdict
Try every startO(N·k·log m)
Correct, far too slow
Min-heap of list headsO(N log k)
Best; one pass over all

k = number of lists, m = longest list, N = total numbers across all lists.

Edge cases to test

  • One list. [[2, 30]] gives [2, 2]: a single number covers the only list.
  • A shared value. When every list holds the same number, the answer has width 0.
  • Tied widths. In Example 1, [6, 9], [7, 10] and [9, 12] all have width 3; the earliest start wins.
  • Lists of length 1. [[5], [1], [9]] has only one choice: [1, 9].
  • Negative numbers. [[-5, -1], [-3, 4]] gives [-3, -1].

Common mistakes

  • Advancing the pointer of the largest value, which can only widen the range.
  • Forgetting to update the largest value when pushing a new number.
  • Continuing after one list runs out, which reports ranges that miss that list.

How to talk through it

  1. 1Clarify. Are the lists sorted? Can they hold duplicates? How do ties between equal widths break?
  2. 2Give the brute force. Fix every start, binary-search each list for its first value ≥ start; too many searches.
  3. 3Find the key move. With one pointer per list, only moving the smallest pointer can ever shrink the range.
  4. 4Code the heap. Min-heap of (value, list, index), plus a running max; pop, record, push the next.
  5. 5Test out loud. Run one list, all lists sharing a value, and the tie in Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?