Sponsored
Sponsored
This approach involves using a priority queue to manage and track the times when servers become available. Specifically, we will use a heap data structure to efficiently find the first available server for a new request. Whenever a request ends, we reassign the server for future tasks. We also utilize a balanced data structure to cycle through the server indexes and track the server with the most handled requests efficiently.
Time complexity: O(n log k), where n is the number of requests, due to the heap operations. Space complexity: O(k + n) for the heaps and request count.
1var busiestServers = function(k, arrival, load) {
2 let available = new Set(Array.from({length: k}, (_, i) => i));
3 let busy = new Map();
4 let requestCount = new Array(k).fill(0);
5 let maxRequests = 0;
6
7 for (let i = 0; i < arrival.length; i++) {
8 let time = arrival[i];
9
10 // Make busy servers available if their load finished
11 for (let [endTime, server] of busy) {
12 if (endTime <= time) {
13 busy.delete(endTime);
14 available.add(server);
15 }
16 }
17
18 if (available.size === 0) continue;
19
20 let index = i % k;
21 let found = false;
22
23 for (let j = 0; j < k; j++) {
24 let server = (index + j) % k;
25 if (available.has(server)) {
26 requestCount[server]++;
27 maxRequests = Math.max(maxRequests, requestCount[server]);
28 available.delete(server);
29 busy.set(time + load[i], server);
30 found = true;
31 break;
32 }
33 }
34 }
35
36 return requestCount.reduce((res, count, server) => (count === maxRequests ? res.concat(server) : res), []);
37};The JavaScript solution uses a `Set` to manage available servers and a `Map` to track busy servers along with their ending times. It iterates through each incoming request and attempts to allocate it to a suitable server index or the next available, cycling through the set if necessary.
The `reduce` function is used to extract the list of the busiest servers at the end.