0% completed
Solution: Problem Challenge 2: Scheduling Tasks
Problem Statement
You are given a list of tasks that need to be run, in any order, on a server. Each task will take one CPU interval to execute but once a task has finished, it has a cooling period during which it can’t be run again. If the cooling period for all tasks is ‘K’ intervals, find the minimum number of CPU intervals that the server needs to finish all tasks.
If at any time the server can’t execute any task then it must stay idle.
Example 1:
Input: [a, a, a, b, c, c], K=2
Output: 7
Explanation: a -> c -> b -> a -> c -> idle -> a
Example 2:
.....
.....
.....
Akaash
· 4 years ago
“ After executing a task we decrease its frequency and put it in a waiting list. In each iteration, we will try to execute as many as k+1 tasks.”
Would be good to explain why and how we get k+1 here. I’m not sure I follow.
hn200000
· 3 years ago
How do you ensure the same task is K distance away if you dump the waiting list to the heap all at once? e.g. - if all tasks in the waiting list have the same frequency, then the last task in the waiting list might happen to be at the root of the heap
Pete Stenger
· 2 years ago
from heapq import * from collections import Counter # We can calculate the solution using a two-part formula. # Observe that we can calculate the length based on the maximum frequency of # a task in the array. Then, we handle an edge case where we have multiple tasks # with maximum frequency. class Solution: def scheduleTasks(self, tasks, k): c = Counter(tasks) heap = [ (-count, char) for char, count in c.items() ] heapify(heap) maxFreq = -heappop(heap)[0] maxFreqCount = 1 while heap and -heap[0][0] == maxFreq: heappop(heap) maxFreqCount += 1 if maxFreqCount > k: return len(tasks) # We will have a char, plus a gap of size k. So k+1. # We repeat this maxFreq - 1 times, as we don't need the last gap.