MEDIUM NC#68 Heap / Priority Queue
621. Task Scheduler
๐ Problem
You are given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
- โขApply Heap reasoning pattern
๐ก Approach
- โ Calculate idle time based on most frequent task
- โ Idle slots = (maxFreq - 1) * n
- โ Fill idle slots with other tasks
- โ Time: O(n), Space: O(1) since only 26 letters
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขCalculate idle time based on most frequent task
- โขIdle slots = (maxFreq - 1) * n
- โขFill idle slots with other tasks
Common Pitfalls
- โขTime: O(n), Space: O(1) since only 26 letters
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
leastInterval(['A','A','A','B','B','B'], 2); Expected:
8 Test Case 2
Not run Input:
leastInterval(['A','C','A','B','D','B'], 1); Expected:
6 Test Case 3
Not run Input:
leastInterval(['A','A','A','B','B','B'], 3); Expected:
10 ๐ Code Editor
๐ค Output