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

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit