Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Problem Challenge 2: Scheduling Tasks
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 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.
A
Anonymous
· 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
Show 1 reply
A
Anonymous
· 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.
Show 2 replies
Reading Progress
0%