NeetCode #259LC-632HardSliding Window
← Back to All Problems#259 · #632 · Smallest Range Covering Elements from K Lists(最小区间)
📌 Problem Statement & Constraints
You are given
k sorted lists of integers in nums. Find the smallest range [a, b] such that at least one number from each list lies within it. Constraints: nums.length == k, 1 <= k <= 3500, 1 <= nums[i].length <= 50, each list is sorted ascending.💡 Core Algorithmic Approaches
- Maintain one pointer per list and a min-heap keyed by the current value from each list.
- The current range is
[heap_min, current_max], wherecurrent_maxis tracked separately as the maximum of the pointers seen so far. - Advance the pointer of the list that contributed the minimum, since any smaller range must exclude that minimum.
- The heap gives the minimum in O(log k), and
current_maxis updated with the newly pushed value.
💻 Benchmark Python3 Implementation
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
import heapq
h = [(lst[0], i, 0) for i, lst in enumerate(nums)]
heapq.heapify(h)
cur_max = max(lst[0] for lst in nums)
best = [h[0][0], cur_max]
while True:
val, i, j = heapq.heappop(h)
if j + 1 == len(nums[i]):
break # this list is exhausted -> stop
nxt = nums[i][j + 1]
heapq.heappush(h, (nxt, i, j + 1))
cur_max = max(cur_max, nxt)
if cur_max - h[0][0] < best[1] - best[0]:
best = [h[0][0], cur_max]
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(N log k) where N is the total number of elements: each element is pushed and popped once.
💾 Space Complexity
O(k) for the heap.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting to stop when a list is exhausted: the range must cover all lists, so once any list runs out, no further improvement is possible.
- Tracking
cur_maxasmax(nums[i][j]): the maximum can come from any list, so it must be maintained incrementally as pointers advance. - Recomputing the range from scratch: O(k) per step; the heap front gives the minimum in O(1).
- Assuming the lists have equal length: they do not, so the exhaustion check must be per list.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
最小区间
你有 k 个 非递减排列 的整数列表。找到一个 最小 区间,使得 k 个列表中的每个列表至少有一个数包含在其中。我们定义如果 b − a < d − c 或者在 b − a == d − c 时 a < c ,则区间 [a, b] 比 [c, d] 小。约束:nums.length == k;1 ≤ k ≤ 3500;1 ≤ nums[i].length ≤ 50;-10^5 ≤ nums[i][j] ≤ 10^5;nums[i] 按非递减顺序排列。
核心要点
- 多路归并 + 最小堆(标准解) :从每个列表中取第一个元素入堆(堆按值排序),同时记录当前所有候选值中的最大值 cur_max 。
- 区间候选 :堆顶是最小值、 cur_max 是最大值,二者构成当前区间 [堆顶, cur_max] 。
- 推进策略 :弹出堆顶元素(来自列表 i 的第 j 个),然后把列表 i 的下一个元素 nums[i][j+1] 入堆,并更新 cur_max 。
- 为什么这样能找到最优 :堆顶是最小值,只有把它替换成它所在列表的下一个元素,才可能让区间左端点右移、从而可能缩小极差。
- 终止条件 :当某个列表的元素被取完时,无法再保证「每个列表都至少有一个数在区间内」,循环结束。
常见陷阱
- 忘记更新 cur_max :新入堆的元素可能成为新的最大值,不更新会导致区间右端点错误。
- 在弹出后、入堆前更新最优区间 :最优区间应基于「当前堆中所有元素」的最小值与最大值。本解在弹出后立即用 v (刚弹出的最小值)与 cur_max 比较,恰好对应「上一轮堆的极值」,逻辑正确且更简洁。
- 终止条件写错 :必须在某个列表耗尽时返回,因为此时已无法保证覆盖所有列表。
- 用「所有元素排序后滑动窗口」 :也可以(把所有 (值, 列表下标) 排序后滑动窗口覆盖 k 个列表),复杂度 O(N log N),比堆的 O(N log k) 略慢但更直观。
- 误以为区间必须由两端的元素构成 :最优区间一定可以取为「某两个实际出现的值」之间的闭区间,因此枚举候选值即可。
参考实现
import heapq
class Solution:
def smallestRange(self, nums: list[list[int]]) -> list[int]:
k = len(nums)
# 堆元素:(值, 所属列表下标, 该列表中的元素下标)
heap = [(row[0], i, 0) for i, row in enumerate(nums)]
heapq.heapify(heap)
cur_max = max(row[0] for row in nums)
best = [heap[0][0], cur_max]
while True:
v, i, j = heapq.heappop(heap)
# 用当前堆顶(最小值)与 cur_max 构成区间,更新最优
if cur_max - v < best[1] - best[0]:
best = [v, cur_max]
# 该列表已耗尽 -> 无法覆盖所有列表,结束
if j + 1 == len(nums[i]):
return best
nxt = nums[i][j + 1]
heapq.heappush(heap, (nxt, i, j + 1))
if nxt > cur_max:
cur_max = nxt