Approach
Breadth-first search
For Minimum Interval to Include Each Query, 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
- 30 lines of Java from the credited upstream file 1851.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 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[] minInterval(int[][] intervals, int[] queries) {3 record T(int size, int right) {}4 int[] ans = new int[queries.length];5 Arrays.fill(ans, -1);6 Queue<T> minHeap = new PriorityQueue<T>(Comparator.comparingInt(T::size));7 Integer[] indices = new Integer[queries.length];8 9 for (int i = 0; i < queries.length; ++i)10 indices[i] = i;11 12 Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));13 Arrays.sort(indices, Comparator.comparingInt(index -> queries[index]));14 15 int i = 0; 16 for (final int index : indices) {17 while (i < intervals.length && intervals[i][0] <= queries[index]) {18 minHeap.offer(new T(intervals[i][1] - intervals[i][0] + 1, intervals[i][1]));19 ++i;20 }21 while (!minHeap.isEmpty() && minHeap.peek().right < queries[index])22 minHeap.poll();23 if (!minHeap.isEmpty())24 ans[index] = minHeap.peek().size;25 }26 27 return ans;28 }29}30