# 621. Task Scheduler

## Problem Statement

<br>

Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. 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.

Return *the least number of units of times that the CPU will take to finish all the given tasks*.

&#x20;

**Example 1:**

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

**Example 2:**

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

**Example 3:**

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

&#x20;

**Constraints:**

* `1 <= task.length <= 104`
* `tasks[i]` is upper-case English letter.
* The integer `n` is in the range `[0, 100]`.

## Intuition

```
Approach:

This is an excellent approach to this problem.
My understanding:

First count the number of occurrences of each element.
Let the max frequency seen be M for element E
We can schedule the first M-1 occurrences of E, each E will be 
followed by at least N CPU cycles in between successive schedules of E

Total CPU cycles after scheduling M-1 occurrences of E = (M-1) * (N + 1) // 
1 comes for the CPU cycle for E itself

Now schedule the final round of tasks. We will need at least 1 CPU cycle 
of the last occurrence of E. If there are multiple 
tasks with frequency M, they will all need 1 more cycle.


Run through the frequency dictionary and for every element which has frequency == M,
 add 1 cycle to result.
 
 
If we have more number of tasks than the max slots we need as computed 
above we will return the length of the tasks array as we need at least those 
many CPU cycles.
```

### Links

<https://leetcode.com/problems/task-scheduler/description/>

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        unordered_map<char,int>mp;
        int count = 0;
        for(auto e : tasks)
        {
            mp[e]++;
            count = max(count, mp[e]);
        }
        
        int ans = (count-1)*(n+1);

        for(auto e : mp) 
            if(e.second == count) 
                ans++;

        return max((int)tasks.size(), ans);
    }
};

//For the return condition to encorporate extra d's or so
// We add the max(tasks.size)
//a a a  b b b  c c c d 
//2

//6+3


//a b c a b c a b c d


```

{% endcode %}

### Approach 2:

```
Heap

Approach:
We want to make, boxes of n+1 Size 
eg- n=2
(A__)A , n+1
So we take out n+1 elemets in heap and add n+1 to count/time
Now at end 

maybe  ....(A only
So we take arr size at end instead of n+1




Similar approach in above optimised
Rather than all of this
We directly take MAx element and for m-1 occurences, make boxes of n+1
for last one, we check for,
if same freq like max

Then only at last count will be increased in last box
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        priority_queue<int> pq;
        unordered_map<char,int> mp;

        for(auto &it: tasks)
            mp[it]++;

        for(auto &it: mp)
            pq.push(it.second);

        int time=0;
        while(!pq.empty()){
            vector<int> temp;
            for(int i=0; i<=n; i++){
                if(!pq.empty()){
                    temp.push_back(pq.top());
                    pq.pop();
                }
            }

            for(auto &it: temp){
                if(it>1)    
                    pq.push(it-1);
            }

            time += pq.empty() ? temp.size() : n+1; 
        }

        return time;
    }
};

```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

\
<https://leetcode.com/problems/reorganize-string/description/>

###


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coding-9.gitbook.io/untitled/hash-and-map/621.-task-scheduler.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
