Find Servers That Handled Most Number of Requests — LeetCode 1606 Python Solution

HardArrayOrdered SetSimulationHeap (Priority Queue)
Problem
#1606
Reading time
4 min

The problem

You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time.

Example

Input
k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]
Output
[1]
Explanation
All of the servers start out available.

Python solution

Python
class Solution:
    def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
        free = SortedList(range(k))
        busy = []
        cnt = [0] * k
        for i, (start, t) in enumerate(zip(arrival, load)):
            while busy and busy[0][0] <= start:
                free.add(busy[0][1])
                heappop(busy)
            if not free:
                continue
            j = free.bisect_left(i % k)
            if j == len(free):
                j = 0
            server = free[j]
            cnt[server] += 1
            heappush(busy, (start + t, server))
            free.remove(server)

        mx = max(cnt)
        return [i for i, v in enumerate(cnt) if v == mx]

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1606. Find Servers That Handled Most Number of Requests is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1606. Find Servers That Handled Most Number of Requests?
LeetCode 1606. Find Servers That Handled Most Number of Requests is rated Hard on LeetCode.
What is the time complexity of LeetCode 1606. Find Servers That Handled Most Number of Requests?
The Python solution on this page runs in O(n log n).
What is the space complexity of LeetCode 1606. Find Servers That Handled Most Number of Requests?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1606. Find Servers That Handled Most Number of Requests cover?
LeetCode 1606. Find Servers That Handled Most Number of Requests is tagged Array, Ordered Set, Simulation and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview