classSolution{public:intleastInterval(vector<char>&tasks,intn){unordered_map<char,int>taskCounts;priority_queue<int>taskQ;// O(t) countfor(autot:tasks){++taskCounts[t];}// O(tlogt) insertfor(auto[t,freq]:taskCounts){taskQ.push(freq);}intcycle=0;while(!taskQ.empty()){vector<int>remainingTasks;intidle=0;intgaps=n;// note while (--i) and while (i--) executes different times// * while (--i) i-1 times// * while (i--) i timeswhile(gaps-->=0){if(!taskQ.empty()){remainingTasks.push_back(taskQ.top());taskQ.pop();++cycle;}else{++idle;}}for(autotf:remainingTasks){if(--tf>0){taskQ.push(tf);}}if(!taskQ.empty()){// to avoid trailing idle timecycle+=idle;}}returncycle;}};