leetcode 621. Task Scheduler (Python)

15 Jul 2020 Leetcode Greedy

621. Task Scheduler (Python)

Greedy.

Description

You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

You need to return the least number of units of times that the CPU will take to finish all the given tasks.

Sample I/O

Example 1

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: 
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.

Example 2

Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.

Example 3

Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16
Explanation: 
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A

Note

  • The number of tasks is in the range [1, 10000].
  • The integer n is in the range [0, 100].

Methodology

The total unit time is length of list + idld time. Count the frequence of each letter. Select the most frequent letter as boundary.The the number of room that between two boundaries is boundary - 1 and the idle time unit will be at least room * n. Split other letters into rooms and each room has no same letters. If all the idle time unit all use out, we are free to expand each room so we do not need more idle time unit. This will give the result as the lenght of the given list. Otherwise if the after fill all tasks into idle time unit and there are still idle time unit not been used then we add length of given list and the available idle time units to get the result.

def leastInterval(self, tasks: List[str], n: int) -> int:
        count=[value for value in Counter(tasks).values()]
        count.sort()
        max_freq=count.pop()
        room=max_freq-1
        idle=(room)*n
        while count and idle > 0:
            idle -= min(room, count.pop())
        return max(0,idle)+len(tasks)

BigO

Time complexity : O(n) as we construct the counter will take O(n) time complexity.

Search

    Table of Contents