621. Task Scheduler
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Heap / Priority Queue
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a list of CPU tasks (labeled A-Z) and a cooldown period `n`, find the minimum number of time units needed to finish all tasks, where identical tasks must be spaced at least `n` intervals apart (idle cycles are inserted as needed).
Approach
- Count the frequency of each task and identify the maximum frequency
f_maxand how many tasks share that frequency (count_max). - The bottleneck is the most frequent task: it forces at least
(f_max - 1) * (n + 1) + count_maxtime slots to satisfy all cooldown constraints. - The actual answer is the maximum of that formula and the total number of tasks — if tasks are dense enough, no idle time is needed at all.
- This greedy math formula eliminates the need for an explicit simulation or heap, giving a clean O(N) solution.
#include <vector>
#include <algorithm>
#include <array>
using namespace std;
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
// Count frequency of each task label.
array<int, 26> freq{};
for (char c : tasks) ++freq[c - 'A'];
// Find the maximum frequency and how many tasks share it.
int f_max = *max_element(freq.begin(), freq.end());
int count_max = (int)count(freq.begin(), freq.end(), f_max);
// Minimum slots needed:
// (f_max - 1) full "frames" of size (n + 1), plus a final partial
// frame containing all tasks tied for the top frequency.
// If tasks are dense, no idles are needed — just use task count.
int min_slots = (f_max - 1) * (n + 1) + count_max;
return max((int)tasks.size(), min_slots);
}
};
Time O(N) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int len=tasks.size();
if(n==0){
return len;
}
int freq[26]={0};
for(const char& c: tasks){
++freq[c-'A'];
}
int max=INT_MIN;
int max_count=0;
for(int i=0; i<26; ++i){
int cur=freq[i];
if(cur>max){
max=cur;
max_count=1;
}
else if(cur==max){
++max_count;
}
}
return std::max(len, (max-1)*(n+1)+max_count);
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.