Task Scheduler n C++

Suppose we have a char array representing tasks CPU need to do. This contains uppercase letters A to Z where different letters represent different tasks. The tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one job or just be idle. However, there is a non-negative cooling interval called n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. We have to find the least number of intervals the CPU will take to finish all the given tasks. So if the input is [A, A, A, B, B, B] and n is 2, then the output will be 8, as A → B → idle → A → B → idle → A → B

To solve this, we will follow these steps −

  • Create a map m, and store the frequency of all characters stored in the task array

  • Define priority queue pq

  • for each key-value pair present at m, insert frequency values into pq

  • ans := 0, cycle := n + 1

  • while pq is not empty

    • define array temp, set time := 0

    • for i in range 0 and pq is not empty, and i − cycle

      • insert top element of pq into temp, delete top from pq, increase temp by 1

    • for i in range 0 to size of temp

      • decrease temp[i] by 1

      • if temp[i] is not 0, then insert temp[i] into pq

    • ans := ans + time when pq is empty, otherwise cycle

  • return ans


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int leastInterval(vector<char>& t, int n) {
      map <char,int> m;
      for(int i =0;i<t.size();i++){
      map <char, int> :: iterator i = m.begin();
      priority_queue <int> pq;
      while(i != m.end()){
      int ans = 0;
      int cycle = n + 1;
         vector <int> temp;
         int time = 0;
         for(int i = 0; !pq.empty() && i < cycle; i++){
         for(int i = 0;i < temp.size(); i++){
            temp[i]-- ;
         ans += pq.empty()? time : cycle;
      return ans;
   vector<char> v = {'A','A','A','B','B','B'};
   Solution ob;
   cout << (ob.leastInterval(v, 2)) ;