1. Cycle-by-Cycle Greedy Simulation
Intuition
Simulate each CPU cycle. Track available cooldown for each task and greedily execute the task with highest remaining frequency.
Algorithm
- Step 1: Count frequency of each task.
- Step 2: Maintain nextAvailable time array of size 26 initialized to 0.
- Step 3: In each time cycle: find available task with maximum remaining frequency.
- Step 4: If found: decrement frequency, set nextAvailable = time + n + 1.
- Step 5: Increment time and repeat until all task frequencies are 0.
- Step 6: Return time.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int leastInterval(vector<char>& tasks, int n) { vector<int> count(26, 0); for (char c : tasks) count[c - 'A']++; vector<int> nextAvail(26, 0); int totalTasks = tasks.size(); int time = 0; while (totalTasks > 0) { int best = -1; for (int i = 0; i < 26; ++i) { if (count[i] > 0 && nextAvail[i] <= time) { if (best == -1 || count[i] > count[best]) { best = i; } } } if (best != -1) { count[best]--; nextAvail[best] = time + n + 1; totalTasks--; } time++; } return time; }}; int main() { Solution sol; vector<char> tasks = {'A', 'A', 'A', 'B', 'B', 'B'}; int n = 2; cout << "Least Intervals: " << sol.leastInterval(tasks, n) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(Total Time * 26) - Space complexity:
O(26)