MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / leastInterval

Method leastInterval

python/0621-task-scheduler.py:2–20  ·  view source on GitHub ↗
(self, tasks: List[str], n: int)

Source from the content-addressed store, hash-verified

1class Solution:
2 def leastInterval(self, tasks: List[str], n: int) -> int:
3 count = Counter(tasks)
4 maxHeap = [-cnt for cnt in count.values()]
5 heapq.heapify(maxHeap)
6
7 time = 0
8 q = deque() # pairs of [-cnt, idleTime]
9 while maxHeap or q:
10 time += 1
11
12 if not maxHeap:
13 time = q[0][1]
14 else:
15 cnt = 1 + heapq.heappop(maxHeap)
16 if cnt:
17 q.append([cnt, time + n])
18 if q and q[0][1] == time:
19 heapq.heappush(maxHeap, q.popleft()[0])
20 return time
21
22
23# Greedy algorithm

Callers

nothing calls this directly

Calls 4

mapFunction · 0.85
popleftMethod · 0.80
maxFunction · 0.50
sumFunction · 0.50

Tested by

no test coverage detected