forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy path621_Task_Scheduler.py
More file actions
44 lines (37 loc) · 1.39 KB
/
621_Task_Scheduler.py
File metadata and controls
44 lines (37 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from heapq import heappush, heappop
from collections import Counter
# Task Scheduler - https://leetcode.com/problems/task-scheduler/
class Solution:
# Uses Heap. inspired from https://tinyurl.com/rmlstk3
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
taskFrequencies = Counter(tasks)
totalIntervals = 0
priorityQueue = []
for k, v in taskFrequencies.items():
heappush(priorityQueue, (-v, k))
while priorityQueue:
currentCoolingInterval, tempTaskHolder = -1, []
while currentCoolingInterval < n:
if priorityQueue:
totalIntervals += 1
currentCoolingInterval += 1
taskFrequency, taskID = heappop(priorityQueue)
if taskFrequency != -1:
tempTaskHolder.append((taskFrequency + 1, taskID))
else:
if tempTaskHolder: # We still have task to process
totalIntervals += (n - currentCoolingInterval)
break
for item in tempTaskHolder:
heappush(priorityQueue, item)
return totalIntervals
sol = Solution()
tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"]
n = 2
output = sol.leastInterval(tasks, n)
print('Res: ', output)