- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 34 lines of Java from the credited upstream file 1942.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
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 smallestChair(int[][] times, int targetFriend) {3 int nextUnsatChair = 0;4 PriorityQueue<Integer> emptyChairs = new PriorityQueue<>();5 PriorityQueue<Pair<Integer, Integer>> occupied =6 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));7 8 for (int i = 0; i < times.length; ++i) {9 int[] time = times[i];10 time = Arrays.copyOf(time, time.length + 1);11 time[time.length - 1] = i;12 times[i] = time;13 }14 15 Arrays.sort(times, Comparator.comparingInt(time -> time[0]));16 17 for (int[] time : times) {18 final int arrival = time[0];19 final int leaving = time[1];20 final int i = time[2];21 while (!occupied.isEmpty() && occupied.peek().getKey() <= arrival)22 emptyChairs.add(occupied.poll().getValue());23 if (i == targetFriend)24 return emptyChairs.isEmpty() ? nextUnsatChair : emptyChairs.peek();25 if (emptyChairs.isEmpty())26 occupied.add(new Pair<>(leaving, nextUnsatChair++));27 else28 occupied.add(new Pair<>(leaving, emptyChairs.poll()));29 }30 31 throw new IllegalArgumentException();32 }33}34