Skip to content

Commit 4ec241a

Browse files
committed
O(nlogn) time and O(n) space using Hashtable and Max Heap with greedy Approach
1 parent 2e4beb9 commit 4ec241a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
3+
4+
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
5+
6+
You need to return the least number of intervals the CPU will take to finish all the given tasks.
7+
8+
9+
10+
Example:
11+
12+
Input: tasks = ["A","A","A","B","B","B"], n = 2
13+
Output: 8
14+
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
15+
16+
17+
Note:
18+
19+
The number of tasks is in the range [1, 10000].
20+
The integer n is in the range [0, 100].
21+
"""
22+
class Solution:
23+
def leastInterval(self, tasks: List[str], n: int) -> int:
24+
hMap = collections.Counter(tasks)
25+
result = 0
26+
maxHeap = [(-val,key) for key,val in hMap.items()]
27+
heapq.heapify(maxHeap)
28+
while maxHeap:
29+
stack,count = [],0
30+
for i in range(n+1):
31+
if maxHeap:
32+
item = heapq.heappop(maxHeap)
33+
count += 1
34+
if item[0] < -1:
35+
stack.append((item[0]+1,item[1]))
36+
for element in stack:
37+
heapq.heappush(maxHeap,element)
38+
if maxHeap:
39+
result += (n+1)
40+
else:
41+
result += count
42+
return result

0 commit comments

Comments
 (0)