Approach
Breadth-first search
For Smallest Range Covering Elements from K Lists, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 35 lines of Java from the credited upstream file 632.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] smallestRange(List<List<Integer>> nums) {3 record T(int i, int j, int num) {} 4 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::num));5 int mn = Integer.MAX_VALUE;6 int mx = Integer.MIN_VALUE;7 8 for (int i = 0; i < nums.size(); ++i) {9 final int num = nums.get(i).get(0);10 minHeap.offer(new T(i, 0, num));11 mn = Math.min(mn, num);12 mx = Math.max(mx, num);13 }14 15 int minRange = mn;16 int maxRange = mx;17 18 while (minHeap.size() == nums.size()) {19 final int i = minHeap.peek().i;20 final int j = minHeap.poll().j;21 if (j + 1 < nums.get(i).size()) {22 minHeap.offer(new T(i, j + 1, nums.get(i).get(j + 1)));23 mx = Math.max(mx, nums.get(i).get(j + 1));24 mn = minHeap.peek().num;25 }26 if (mx - mn < maxRange - minRange) {27 minRange = mn;28 maxRange = mx;29 }30 }31 32 return new int[] {minRange, maxRange};33 }34}35