Skip to main content
Back to problems
#621
Medium Algorithms

Task scheduler

Array Hash Table Greedy Sorting Heap (Priority Queue) Counting
62.7% acceptance
Feb 20, 2026
11731
2215
Given an array of CPU tasks labeled A-Z and a number n (cooldown period), return the minimum number of CPU intervals required to complete all tasks.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn least_interval(tasks: Vec<char>, n: i32) -> i32 {
    let mut freq = [0i32; 26];
    for t in &tasks {
      freq[(*t as u8 - b'A') as usize] += 1;
    }
    freq.sort_unstable();
    let max_freq = freq[25];
    let max_count = freq.iter().filter(|&&f| f == max_freq).count() as i32;
    let min_len = (max_freq - 1) * (n + 1) + max_count;
    min_len.max(tasks.len() as i32)
  }
}