Skip to main content
Back to problems
#2365
Medium Algorithms

Task scheduler ii

Array Hash Table Simulation
54.7% acceptance
Feb 25, 2026
619
76
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Complete the next task from tasks, or Take a break. Return the minimum number of days needed to complete all tasks.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;


impl Solution {
  pub fn task_scheduler_ii(tasks: Vec<i32>, space: i32) -> i64 {
    let space = space as i64;
    let mut last_done: HashMap<i32, i64> = HashMap::new();
    let mut day = 0i64;
    for task in tasks {
      day += 1;
      if let Some(&ld) = last_done.get(&task) {
        let earliest = ld + space + 1;
        if day < earliest { day = earliest; }
      }
      last_done.insert(task, day);
    }
    day
  }
}