- 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
- 70 lines of Python from the credited upstream file find-servers-that-handled-most-number-of-requests.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit 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.
123 4import itertools5import heapq6 7 8class Solution(object):9 def busiestServers(self, k, arrival, load):10 """11 :type k: int12 :type arrival: List[int]13 :type load: List[int]14 :rtype: List[int]15 """16 count = [0]*k17 min_heap_of_endtimes = []18 min_heap_of_nodes_after_curr = []19 min_heap_of_nodes_before_curr = range(k)20 for i, (t, l) in enumerate(itertools.izip(arrival, load)):21 if i % k == 0:22 min_heap_of_nodes_before_curr, min_heap_of_nodes_after_curr = [], min_heap_of_nodes_before_curr23 while min_heap_of_endtimes and min_heap_of_endtimes[0][0] <= t:24 _, free = heapq.heappop(min_heap_of_endtimes)25 if free < i % k:26 heapq.heappush(min_heap_of_nodes_before_curr, free)27 else:28 heapq.heappush(min_heap_of_nodes_after_curr, free)29 min_heap_of_candidates = min_heap_of_nodes_after_curr if min_heap_of_nodes_after_curr else min_heap_of_nodes_before_curr30 if not min_heap_of_candidates:31 continue32 node = heapq.heappop(min_heap_of_candidates)33 count[node] += 134 heapq.heappush(min_heap_of_endtimes, (t+l, node))35 max_count = max(count)36 return [i for i in xrange(k) if count[i] == max_count]37 38 394041import sortedcontainers 42import itertools43import heapq44 45 4647class Solution2(object):48 def busiestServers(self, k, arrival, load):49 """50 :type k: int51 :type arrival: List[int]52 :type load: List[int]53 :rtype: List[int]54 """55 count = [0]*k 56 min_heap_of_endtimes = []57 availables = sortedcontainers.SortedList(xrange(k)) 58 for i, (t, l) in enumerate(itertools.izip(arrival, load)):59 while min_heap_of_endtimes and min_heap_of_endtimes[0][0] <= t:60 _, free = heapq.heappop(min_heap_of_endtimes) 61 availables.add(free) 62 if not availables: 63 continue64 idx = availables.bisect_left(i % k) % len(availables) 65 node = availables.pop(idx) 66 count[node] += 167 heapq.heappush(min_heap_of_endtimes, (t+l, node)) 68 max_count = max(count)69 return [i for i in xrange(k) if count[i] == max_count]70