Approach
Breadth-first search
For Find Servers That Handled Most Number of Requests, 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
- 42 lines of Java from the credited upstream file 1606.java.
- The implementation visibly relies on sequence storage, ordered lookup, 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 List<Integer> busiestServers(int k, int[] arrival, int[] load) {3 List<Integer> ans = new ArrayList<>();4 int[] times = new int[k];5 TreeSet<Integer> idleServers = new TreeSet<>();6 7 Queue<Pair<Integer, Integer>> minHeap =8 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));9 10 for (int i = 0; i < k; ++i)11 idleServers.add(i);12 13 for (int i = 0; i < arrival.length; ++i) {14 15 while (!minHeap.isEmpty() && minHeap.peek().getKey() <= arrival[i]) {16 idleServers.add(minHeap.peek().getValue());17 minHeap.poll();18 }19 20 final int server = getNextAvailableServer(idleServers, i, k);21 if (server == -1)22 continue;23 ++times[server];24 minHeap.offer(new Pair<>(arrival[i] + load[i], server));25 idleServers.remove(server);26 }27 28 final int busiest = Arrays.stream(times).max().getAsInt();29 for (int i = 0; i < k; ++i)30 if (times[i] == busiest)31 ans.add(i);32 return ans;33 }34 35 private int getNextAvailableServer(TreeSet<Integer> idleServers, int ithRequest, int k) {36 if (idleServers.isEmpty())37 return -1;38 Integer server = idleServers.ceiling(ithRequest % k);39 return server == null ? idleServers.first() : server;40 }41}42