-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0621_task_scheduler.html
More file actions
565 lines (493 loc) · 19.8 KB
/
0621_task_scheduler.html
File metadata and controls
565 lines (493 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>621 - Task Scheduler</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#621</span> Task Scheduler</h1>
<p>
Given an array of tasks and a cooldown period n, find the minimum time needed to complete all tasks.
The same task must have at least n time units between executions.
</p>
<div class="problem-meta">
<span class="meta-tag">📝 Algorithm</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0621_task_scheduler/0621_task_scheduler.py</code>
</div>
<h3>Example:</h3>
<pre>
tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Schedule: A → B → idle → A → B → idle → A → B
</pre>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<label>Cooldown n = <input type="number" id="nInput" value="2" min="0" max="5" style="width: 50px; padding: 5px;"></label>
<button id="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn btn-success">Auto Run</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Schedule tasks with cooldown constraint</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
import heapq
from collections import Counter
"""
LeetCode Task Scheduler
Problem from LeetCode: https://leetcode.com/problems/task-scheduler/
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 in the array), that is that there must be at least n units of time between any two same tasks.
Return the least number of units of time that the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation:
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.
Example 2:
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.
Example 3:
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16
Explanation:
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A
Constraints:
- 1 <= task.length <= 10^4
- tasks[i] is upper-case English letter.
- The integer n is in the range [0, 100].
"""
class Solution:
def least_interval(self, tasks: List[str], n: int) ->int:
"""
Find the least number of units of time needed to complete all tasks.
Args:
tasks: List of tasks where each capital letter represents a different task
n: Minimum units of time between two same tasks
Returns:
int: The least units of time needed to complete all tasks
"""
task_counts = Counter(tasks)
max_heap = [(-count) for count in task_counts.values()]
heapq.heapify(max_heap)
time = 0
while max_heap:
temp = []
for _ in range(n + 1):
if max_heap:
freq = heapq.heappop(max_heap)
freq += 1
if freq < 0:
temp.append(freq)
else:
break
for freq in temp:
heapq.heappush(max_heap, freq)
if max_heap:
time += n + 1
else:
time += len(temp)
return time
def leastInterval_math(self, tasks: List[str], n: int) ->int:
"""
Uses a mathematical formula to calculate the minimum time.
Args:
tasks: List of tasks represented as capital letters
n: Minimum units of time between two same tasks
Returns:
int: The least units of time needed to complete all tasks
"""
counts = list(Counter(tasks).values())
max_count = max(counts)
max_count_occurrences = counts.count(max_count)
time = (max_count - 1) * (n + 1) + max_count_occurrences
return max(time, len(tasks))
def leastInterval_queue(self, tasks: List[str], n: int) ->int:
"""
Implementation using a queue to track when tasks become available again.
Args:
tasks: List of tasks represented as capital letters
n: Minimum units of time between two same tasks
Returns:
int: The least units of time needed to complete all tasks
"""
from collections import deque
frequencies = Counter(tasks)
sorted_freqs = sorted(frequencies.values(), reverse=True)
queue = deque([(0, count) for count in sorted_freqs])
current_time = 0
while queue:
next_time, count = queue.popleft()
current_time = max(current_time, next_time)
count -= 1
current_time += 1
if count > 0:
queue.append((current_time + n, count))
queue = deque(sorted(queue, key=lambda x: (x[0], -x[1])))
return current_time
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
tasks = ["A","A","A","B","B","B"]
n = 2
result = solution.least_interval(tasks, n)
print(f"Example 1: {result}") # Expected: 8
# Example 2
tasks = ["A","A","A","B","B","B"]
n = 0
result = solution.least_interval(tasks, n)
print(f"Example 2: {result}") # Expected: 6
# Example 3
tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"]
n = 2
result = solution.least_interval(tasks, n)
print(f"Example 3: {result}") # Expected: 16
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const tasks = ["A", "A", "A", "B", "B", "B"];
const taskColors = {
"A": "#3b82f6",
"B": "#10b981",
"C": "#f59e0b",
"idle": "#94a3b8"
};
let n = 2;
let maxHeap = []; // [{task, count}]
let schedule = [];
let currentTime = 0;
let isRunning = false;
let cycleStep = 0;
let cycleTemp = [];
let done = false;
function countTasks() {
const counts = {};
for (const t of tasks) {
counts[t] = (counts[t] || 0) + 1;
}
return counts;
}
function heapPush(heap, item) {
heap.push(item);
let i = heap.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (heap[i].count > heap[parent].count) {
[heap[i], heap[parent]] = [heap[parent], heap[i]];
i = parent;
} else break;
}
}
function heapPop(heap) {
if (heap.length === 0) return null;
const top = heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
let i = 0;
while (true) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let largest = i;
if (left < heap.length && heap[left].count > heap[largest].count) {
largest = left;
}
if (right < heap.length && heap[right].count > heap[largest].count) {
largest = right;
}
if (largest !== i) {
[heap[i], heap[largest]] = [heap[largest], heap[i]];
i = largest;
} else break;
}
return top;
}
function render() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", width / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Task Scheduler (cooldown n = ${n})`);
// Task counts / Max Heap
const heapG = svg.append("g").attr("transform", "translate(100, 80)");
heapG.append("text")
.attr("x", 0)
.attr("y", 0)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Max Heap (by count):");
if (maxHeap.length === 0 && !done) {
heapG.append("text")
.attr("x", 0)
.attr("y", 30)
.attr("font-size", "14px")
.attr("fill", "#64748b")
.text("Empty");
} else {
const sortedHeap = [...maxHeap].sort((a, b) => b.count - a.count);
sortedHeap.forEach((item, i) => {
heapG.append("rect")
.attr("x", i * 70)
.attr("y", 15)
.attr("width", 60)
.attr("height", 50)
.attr("rx", 8)
.attr("fill", taskColors[item.task] || "#64748b")
.attr("opacity", 0.8);
heapG.append("text")
.attr("x", i * 70 + 30)
.attr("y", 35)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "white")
.text(item.task);
heapG.append("text")
.attr("x", i * 70 + 30)
.attr("y", 55)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "white")
.text(`×${item.count}`);
});
}
// Current cycle info
const cycleG = svg.append("g").attr("transform", "translate(500, 80)");
cycleG.append("text")
.attr("x", 0)
.attr("y", 0)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Current Cycle (${n + 1} slots):`);
for (let i = 0; i < n + 1; i++) {
const slotTask = cycleTemp[i];
cycleG.append("rect")
.attr("x", i * 55)
.attr("y", 15)
.attr("width", 50)
.attr("height", 50)
.attr("rx", 8)
.attr("fill", slotTask ? (taskColors[slotTask.task] || "#64748b") : "#e2e8f0")
.attr("stroke", i === cycleStep && !done ? "#f59e0b" : "#94a3b8")
.attr("stroke-width", i === cycleStep && !done ? 3 : 1);
if (slotTask) {
cycleG.append("text")
.attr("x", i * 55 + 25)
.attr("y", 45)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "white")
.text(slotTask.task);
} else {
cycleG.append("text")
.attr("x", i * 55 + 25)
.attr("y", 45)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#94a3b8")
.text(i < cycleStep ? "idle" : "?");
}
}
// Schedule timeline
const timelineG = svg.append("g").attr("transform", "translate(50, 200)");
timelineG.append("text")
.attr("x", 0)
.attr("y", 0)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Schedule Timeline:");
const slotWidth = 50;
const slotsPerRow = 15;
schedule.forEach((task, i) => {
const row = Math.floor(i / slotsPerRow);
const col = i % slotsPerRow;
const x = col * (slotWidth + 5);
const y = 20 + row * 70;
timelineG.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", slotWidth)
.attr("height", 50)
.attr("rx", 6)
.attr("fill", taskColors[task] || "#94a3b8");
timelineG.append("text")
.attr("x", x + slotWidth / 2)
.attr("y", y + 25)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "white")
.text(task);
timelineG.append("text")
.attr("x", x + slotWidth / 2)
.attr("y", y + 42)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "rgba(255,255,255,0.8)")
.text(`t=${i}`);
});
// Time counter
svg.append("text")
.attr("x", width - 50)
.attr("y", 30)
.attr("text-anchor", "end")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Total Time: ${schedule.length}`);
// Legend
const legend = svg.append("g").attr("transform", `translate(20, ${height - 50})`);
Object.entries(taskColors).forEach(([task, color], i) => {
legend.append("rect")
.attr("x", i * 100)
.attr("y", 0)
.attr("width", 20)
.attr("height", 20)
.attr("rx", 4)
.attr("fill", color);
legend.append("text")
.attr("x", i * 100 + 28)
.attr("y", 15)
.attr("font-size", "12px")
.text(task === "idle" ? "Idle" : `Task ${task}`);
});
}
function reset() {
n = parseInt(document.getElementById("nInput").value) || 2;
const counts = countTasks();
maxHeap = [];
for (const [task, count] of Object.entries(counts)) {
heapPush(maxHeap, { task, count });
}
schedule = [];
currentTime = 0;
cycleStep = 0;
cycleTemp = [];
isRunning = false;
done = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = `Schedule tasks with cooldown n = ${n}`;
render();
}
function step() {
if (done) {
document.getElementById("status").textContent = `Complete! Total time: ${schedule.length}`;
return;
}
if (maxHeap.length === 0 && cycleTemp.length === 0) {
done = true;
document.getElementById("status").textContent = `Complete! Total time: ${schedule.length}`;
render();
return;
}
// Within a cycle
if (cycleStep < n + 1) {
if (maxHeap.length > 0) {
const item = heapPop(maxHeap);
schedule.push(item.task);
item.count--;
if (item.count > 0) {
cycleTemp.push(item);
} else {
cycleTemp.push(null);
}
document.getElementById("status").textContent =
`Cycle slot ${cycleStep}: Execute task ${item.task}`;
} else if (cycleTemp.some(t => t)) {
// Need idle
schedule.push("idle");
cycleTemp.push(null);
document.getElementById("status").textContent =
`Cycle slot ${cycleStep}: Idle (no available tasks)`;
}
cycleStep++;
}
// End of cycle - restore tasks to heap
if (cycleStep >= n + 1) {
for (const item of cycleTemp) {
if (item && item.count > 0) {
heapPush(maxHeap, item);
}
}
cycleTemp = [];
cycleStep = 0;
if (maxHeap.length === 0) {
done = true;
document.getElementById("status").textContent = `Complete! Total time: ${schedule.length}`;
}
}
render();
}
async function autoRun() {
if (isRunning) {
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
return;
}
isRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
while (!done && isRunning) {
step();
await new Promise(r => setTimeout(r, 600));
}
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
document.getElementById("nInput").addEventListener("change", reset);
reset();
</script>
</body>
</html>