Bird
Raised Fist0

Given the following code for the Task Scheduler, what is the returned value for leastInterval(['A','A','B'], 2)?

easy🧾 Code Trace Q12 of Q15
Greedy Algorithms - Task Scheduler (CPU Cooling)
Given the following code for the Task Scheduler, what is the returned value for leastInterval(['A','A','B'], 2)?
A3
B5
C6
D4
Step-by-Step Solution
  1. Step 1: Initialize frequencies and max-heap

    Tasks: A(2), B(1). Max-heap: [-2, -1].
  2. Step 2: Simulate scheduling cycles

    Cycle 1: pop -2 (A), decrement to -1 and store; pop -1 (B), decrement to 0 ignore; cycle=2, heap not empty -> time += n+1=3.
    Cycle 2: pop -1 (A), decrement to 0 ignore; cycle=1, heap empty -> time += cycle=1.
    Total time = 3 + 1 = 4.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Manual simulation matches 4 units [OK]
Quick Trick: Count cycles and add idle if heap not empty [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in cycle count
  • Adding n+1 even when heap empty
  • Ignoring decrement of counts
Trap Explanation:
PITFALL
  • Candidates often add full cooldown even when tasks finish early, overestimating time.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute heap-based greedy scheduling and track time correctly.
Master "Task Scheduler (CPU Cooling)" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes