{"id":"task-scheduler","title":"Task Scheduler","difficulty":"medium","patterns":["heap"],"primaryConcept":"heap-stream","concepts":["heap-stream","hash-map-grouping"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string-list","primaryParam":"tasks","sizeMetric":"length","allowedStrings":["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],"secondaryParams":{"n":{"strategy":"random-int","value":{"min":0,"max":20}}}},"description":"Given a list of CPU tasks represented by letters and a non-negative cooldown `n`, return the least number of time intervals needed to finish all tasks.\n\nRequirements:\n- Each interval can run one task or stay idle.\n- Two executions of the same task must be separated by at least `n` intervals.\n- Tasks may be run in any order.","examples":[{"input":"tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2","output":"8","explanation":"One optimal schedule is A, B, idle, A, B, idle, A, B."},{"input":"tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 0","output":"6","explanation":"With no cooldown, every interval can run a task."},{"input":"tasks = [\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\"], n = 2","output":"10","explanation":"The frequent A tasks force idle slots between their runs."}],"constraints":[{"id":"1-len-tasks-10-4","text":"1 <= len(tasks) <= 10^4","check":{"kind":"sizeRange","target":"tasks","measure":"arrayLength","min":1,"max":10000}},{"id":"0-n-100","text":"0 <= n <= 100","check":{"kind":"valueRange","target":"n","selector":"value","min":0,"max":100}},{"id":"each-task-is-an-uppercase-english-letter","text":"Each task is an uppercase English letter","check":{"kind":"domain","target":"tasks","selector":"arrayItems","allowed":["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]}}],"starterCode":"class Solution:\n    def leastInterval(self, tasks: list[str], n: int) -> int:\n        # Your code here\n        pass","functionName":"leastInterval","testCases":[{"id":"1","input":{"tasks":["A","A","A","B","B","B"],"n":2},"expected":8,"description":"Canonical two-task cooldown schedule."},{"id":"2","input":{"tasks":["A","A","A","B","B","B"],"n":0},"expected":6,"description":"No cooldown means no idle intervals."},{"id":"3","input":{"tasks":["A","A","A","A","B","C","D"],"n":2},"expected":10,"description":"One dominant task forces idle slots."},{"id":"4","input":{"tasks":["A","B","C","D"],"n":3},"expected":4,"description":"All tasks are distinct."},{"id":"5","input":{"tasks":["A","A","A","B","B","B","C","C","D","D"],"n":2},"expected":10,"description":"Enough other tasks fill the cooldown gaps."},{"id":"h1","input":{"tasks":["A"],"n":100},"expected":1,"description":"Single task."},{"id":"h2","input":{"tasks":["A","A","B","B","C","C"],"n":3},"expected":7,"description":"Multiple tasks tie for max frequency."},{"id":"h3","input":{"tasks":["A","A","A","A","A","A","B"],"n":2},"expected":16,"description":"Large idle gap caused by one task."},{"id":"h4","input":{"tasks":["A","A","A","B","B","B","C"],"n":2},"expected":8},{"id":"h5","input":{"tasks":["A","B","C","D","E"],"n":4},"expected":5},{"id":"topup-no-cooldown","input":{"tasks":["A","A","B","C"],"n":0},"expected":4,"description":"No cooldown means runtime equals the task count."},{"id":"topup-three-way-tie","input":{"tasks":["A","A","A","B","B","B","C","C","C"],"n":2},"expected":9,"description":"Three max-frequency tasks fill the cooldown frame without idle slots."}],"hints":[{"level":1,"content":"Which task should run next if several tasks are available?","revealPattern":false},{"level":2,"content":"Run the task with the highest remaining frequency, then place it into a cooldown queue if it still has work left.","revealPattern":true},{"level":3,"content":"A max-heap can be simulated by pushing negative counts into Python's min-heap.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach selects ready tasks without scanning every type?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"simulate-heap","name":"Heap simulation with cooldown","summary":"Count tasks, repeatedly pop the largest remaining count, and delay unfinished work in a cooldown queue.","decisionReason":"A heap hands back the most frequent ready task in log time, so each interval picks its task without re-reading every type.","complexity":{"time":"O(T log U)","space":"O(U)"},"tradeoffs":["Runs in O(T log U) time and uses O(U) space."],"isOptimal":true},{"id":"scan-each-time","name":"Scan every task type each interval","summary":"At every time step, search all task types for the best available task.","decisionReason":"This still returns the right schedule, but re-reading all U types every interval is the slower cost the heap avoids.","complexity":{"time":"O(T * U)","space":"O(U)"},"tradeoffs":["Runs in O(T * U) time and uses O(U) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"count-frequencies","title":"Count task frequencies","description":"Build a count for each task type before scheduling.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Counting only distinct task names","Overwriting counts instead of incrementing them"],"hint":"Use a dictionary keyed by task letter.","semanticSpec":{"intent":"Build reusable frequency state for task counts.","doneWhen":"Each task occurrence increments the count for that task key.","mustProve":["A keyed counter is updated while scanning tasks."],"mustNotAccept":["A set of task names without counts."],"proofSnippets":[{"id":"py-task-scheduler-counts","language":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    counts = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n    return len(counts)"}],"roles":["task key","frequency map"]}},{"id":"seed-heap","title":"Seed the priority heap","description":"Push each task frequency into a heap so the largest remaining count is selected first.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"seed-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Pushing task names instead of remaining counts","Forgetting to preserve max-priority ordering for counts"],"hint":"Use the heap ordering needed for the largest remaining count to come out first.","semanticSpec":{"intent":"Populate a heap from the frequency values.","doneWhen":"The heap receives the task-count values before the scheduling loop.","mustProve":["A priority storage is initialized and seeded from counted values."],"mustNotAccept":["Scheduling without a priority structure."],"proofSnippets":[{"id":"py-task-scheduler-seed-heap","language":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    counts = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n    heap = []\n    for count in counts.values():\n        heappush(heap, -count)\n    return len(heap)"}],"roles":["frequency values","priority heap"]}},{"id":"run-cycle","title":"Run one available task per interval","description":"Advance time and pop one available task from the heap each scheduling interval.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop","readMode":"heap-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]}]},"commonMistakes":["Running more than one task in one interval","Forgetting to count idle intervals"],"hint":"Increment `time` once each loop, whether or not the heap has a task.","semanticSpec":{"intent":"Model each interval as one tick that may pop one heap task.","doneWhen":"The loop increments elapsed time and extracts from the heap when work is available.","mustProve":["A heap extract happens in a loop with elapsed time state."],"mustNotAccept":["A loop that never advances elapsed time."],"roles":["elapsed time","selected task count"]}},{"id":"cooldown-cycle","title":"Respect task cooldown","description":"Delay unfinished work until its ready time before putting it back into the heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"uses_event_scheduled_selection","scope":"cooldown-cycle","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Putting a task back into the heap immediately when `n > 0`","Using `time + n + 1` after already counting the current interval"],"hint":"If time starts after the current task runs, `time + n` is the next valid ready time.","semanticSpec":{"intent":"Represent cooldown as delayed availability before heap selection resumes.","doneWhen":"The scheduler uses heap selection together with delayed availability state.","mustProve":["Priority selection is coupled to event-scheduled availability."],"mustNotAccept":["Immediate heap reinsertion with no cooldown state."],"roles":["ready time","cooldown queue","heap availability"]}},{"id":"return-time","title":"Return elapsed intervals","description":"Return the elapsed time after both the heap and cooldown queue are empty.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the number of tasks instead of intervals","Stopping when the heap is empty while cooldown still has work"],"hint":"The answer is the `time` accumulator after all work has been consumed.","semanticSpec":{"intent":"Return the completed schedule length.","doneWhen":"The returned value is the terminal elapsed-time state.","mustProve":["A numeric state updated by the loop is returned."],"mustNotAccept":["Returning the heap size or frequency map size."],"roles":["elapsed time","answer"]}}],"slides":[{"id":"opener","chapter":"Understand","kind":"info","eyebrow":"Read the problem","title":"Schedule the tasks in the fewest intervals","workspacePanel":"problem","body":["A CPU runs one task per interval. The same task cannot run twice within n intervals of itself, so after running a task you wait at least n intervals before running it again. When nothing is allowed to run, the CPU sits idle for that interval, and an idle interval still counts.","You may choose the task order, but frequent task types can exhaust all other ready work before their cooldown ends. Those gaps force idle intervals into the shortest schedule."]},{"id":"brute-force","chapter":"The slow way","kind":"code-trace","source":"brute-force","eyebrow":"Start naive","title":"Each interval, scan every task type for the best one to run","summary":"A direct simulation keeps a count per task and a next-ready time per task. Every interval it walks all the task types looking for the best one to run, runs it, and parks it until its cooldown ends. Watch how much of that walk is wasted.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    counts: dict[str, int] = {}\n    ready: dict[str, int] = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n        ready[task] = 0\n    remaining = len(tasks)\n    time = 0\n    while remaining > 0:\n        time = time + 1\n        best = -1\n        chosen = \"\"\n        for task in counts:\n            if ready[task] <= time and counts[task] > best:\n                best = counts[task]\n                chosen = task\n        if best > 0:\n            counts[chosen] = counts[chosen] - 1\n            ready[chosen] = time + n\n            remaining = remaining - 1\n    return time","steps":[{"id":"s1","title":"Interval 1 scans A and B, runs A","codeLine":13,"summary":"Both A and B count 3 and both are ready, so the scan reads every task type just to learn A is a top choice. A runs, drops to 2, and is parked until interval 3.","state":{"arrays":[{"name":"counts","values":[3,3],"current":0}],"labels":{"time":"time"},"time":1}},{"id":"s2","title":"Interval 2 scans again, runs B","codeLine":13,"summary":"A is still cooling down, so the scan walks both task types again and settles on B. B runs, drops to 2, and is parked until interval 4.","state":{"arrays":[{"name":"counts","values":[2,3],"current":1}],"time":2}},{"id":"s3","title":"Interval 3 scans, finds nothing ready, idles","codeLine":13,"summary":"A becomes ready exactly at interval 3, but the scan still has to read every task type to discover that. A runs and the clock keeps ticking.","state":{"arrays":[{"name":"counts","values":[2,2],"current":0}],"time":3}},{"id":"s4","title":"Every interval pays for a full scan","codeLine":14,"summary":"Eight intervals finish the schedule, and each one walks the whole list of task types before choosing. With only two types that is cheap, but the scan grows with the number of distinct tasks.","state":{"arrays":[{"name":"counts","values":[0,0],"current":0}],"time":8}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nconst ready = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task) : 0) + 1);\n    ready.set(task, 0);\n}\nlet remaining = tasks.length;\nlet time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    let best = -1;\n    let chosen = \"\";\n    for (const task of counts.keys()) {\n        if (ready.get(task) <= time && counts.get(task) > best) {\n            best = counts.get(task);\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts.set(chosen, (counts.get(chosen) - 1));\n        ready.set(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}},"alternateStyles":{"close-to-source":{"code":"const counts = new Map();\nconst ready = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task) : 0) + 1);\n    ready.set(task, 0);\n}\nlet remaining = tasks.length;\nlet time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    let best = -1;\n    let chosen = \"\";\n    for (const task of counts.keys()) {\n        const leftValue = ready.get(task);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        let condition = leftValue <= time;\n        if (condition) {\n            const leftValue2 = counts.get(task);\n            if (leftValue2 === undefined) throw new Error(\"KeyError\");\n            condition = leftValue2 > best;\n        }\n        if (condition) {\n            const bestValue = counts.get(task);\n            if (bestValue === undefined) throw new Error(\"KeyError\");\n            best = bestValue;\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        const keyValue = chosen;\n        const leftValue = counts.get(chosen);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        counts.set(keyValue, (leftValue - 1));\n        ready.set(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":23,"16":26,"17":29,"18":30,"19":34,"20":35,"21":38},"statementBundles":{"6":{"startLine":5,"endLine":6},"14":{"startLine":14,"endLine":22},"15":{"startLine":23,"endLine":25},"16":{"startLine":26,"endLine":28},"18":{"startLine":30,"endLine":33},"20":{"startLine":35,"endLine":37}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<string, number> = new Map();\nconst ready: Map<string, number> = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task)! : 0) + 1);\n    ready.set(task, 0);\n}\nlet remaining = tasks.length;\nlet time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    let best = -1;\n    let chosen = \"\";\n    for (const task of counts.keys()) {\n        if (ready.get(task)! <= time && counts.get(task)! > best) {\n            best = counts.get(task)!;\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts.set(chosen, (counts.get(chosen)! - 1));\n        ready.set(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}},"alternateStyles":{"close-to-source":{"code":"const counts: Map<string, number> = new Map();\nconst ready: Map<string, number> = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task)! : 0) + 1);\n    ready.set(task, 0);\n}\nlet remaining = tasks.length;\nlet time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    let best = -1;\n    let chosen = \"\";\n    for (const task of counts.keys()) {\n        const leftValue = ready.get(task);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        let condition = leftValue <= time;\n        if (condition) {\n            const leftValue2 = counts.get(task);\n            if (leftValue2 === undefined) throw new Error(\"KeyError\");\n            condition = leftValue2 > best;\n        }\n        if (condition) {\n            const bestValue = counts.get(task);\n            if (bestValue === undefined) throw new Error(\"KeyError\");\n            best = bestValue;\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        const keyValue = chosen;\n        const leftValue = counts.get(chosen);\n        if (leftValue === undefined) throw new Error(\"KeyError\");\n        counts.set(keyValue, (leftValue - 1));\n        ready.set(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":23,"16":26,"17":29,"18":30,"19":34,"20":35,"21":38},"statementBundles":{"6":{"startLine":5,"endLine":6},"14":{"startLine":14,"endLine":22},"15":{"startLine":23,"endLine":25},"16":{"startLine":26,"endLine":28},"18":{"startLine":30,"endLine":33},"20":{"startLine":35,"endLine":37}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<String, Integer> counts = new HashMap<String, Integer>();\nMap<String, Integer> ready = new HashMap<String, Integer>();\nfor (String task : tasks) {\n    counts.put(task, (counts.getOrDefault(task, 0) + 1));\n    ready.put(task, 0);\n}\nint remaining = tasks.size();\nint time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    int best = -1;\n    String chosen = \"\";\n    for (String task : counts.keySet()) {\n        if ((ready.get(task) <= time && counts.get(task) > best)) {\n            best = counts.get(task);\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts.put(chosen, (counts.get(chosen) - 1));\n        ready.put(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}},"alternateStyles":{"close-to-source":{"code":"Map<String, Integer> counts = new HashMap<String, Integer>();\nMap<String, Integer> ready = new HashMap<String, Integer>();\nfor (String task : tasks) {\n    counts.put(task, (counts.getOrDefault(task, 0) + 1));\n    ready.put(task, 0);\n}\nint remaining = tasks.size();\nint time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    int best = -1;\n    String chosen = \"\";\n    for (String task : counts.keySet()) {\n        if ((requireMapValue(ready, task) <= time && requireMapValue(counts, task) > best)) {\n            best = requireMapValue(counts, task);\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts.put(chosen, (counts.get(chosen) - 1));\n        ready.put(chosen, (time + n));\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<string, int> counts = new();\nDictionary<string, int> ready = new();\nforeach (string task in tasks) {\n    counts[task] = (counts.ContainsKey(task) ? counts[task] : 0) + 1;\n    ready[task] = 0;\n}\nint remaining = tasks.Count;\nint time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    int best = -1;\n    string chosen = \"\";\n    foreach (string task in counts.Keys) {\n        if (ready[task] <= time && counts[task] > best) {\n            best = counts[task];\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts[chosen] = counts[chosen] - 1;\n        ready[chosen] = time + n;\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<string, int> counts;\nunordered_map<string, int> ready;\nfor (string task : tasks) {\n    counts[task] += 1;\n    ready[task] = 0;\n}\nint remaining = tasks.size();\nint time = 0;\nwhile (remaining > 0) {\n    time = time + 1;\n    int best = -1;\n    string chosen = \"\";\n    for (const auto& [task, value] : counts) {\n        if ((ready.at(task) <= time && counts.at(task) > best)) {\n            best = counts.at(task);\n            chosen = task;\n        }\n    }\n    if (best > 0) {\n        counts[chosen] = (counts.at(chosen) - 1);\n        ready[chosen] = (time + n);\n        remaining = remaining - 1;\n    }\n}\nreturn time;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":19,"18":20,"19":21,"20":22,"21":25},"statementBundles":{"6":{"startLine":5,"endLine":6},"16":{"startLine":16,"endLine":18},"20":{"startLine":22,"endLine":24}}}}}},{"id":"cost-probe","chapter":"The slow way","kind":"case-probe","eyebrow":"Count the cost","title":"What does scanning every task type each interval cost?","summary":"The trace returns to the same inner loop every interval, reading all the task types before it picks one.","workspacePanel":"trace","options":[{"id":"intervals-times-types","label":"One full scan per interval, so the total intervals times the number of task types","rationale":"Every interval walks all U task types to find the best ready one, and there are as many intervals as the schedule is long, so the work is the schedule length times U.","isCorrect":true},{"id":"one-pass","label":"A single pass over the tasks, so linear overall","rationale":"A single pass would read each task once, but this plan re-reads every task type at every interval rather than once.","isCorrect":false},{"id":"log-time","label":"A logarithmic lookup per interval","rationale":"A scan that checks every task type is linear in the number of types, not logarithmic; nothing here narrows the search by halving it.","isCorrect":false}],"answer":"Each interval scans all U task types just to find the most frequent ready one, and the schedule runs for as many intervals as it takes, so the cost is roughly the schedule length times U. The repeated scan for one maximum is the work to cut."},{"id":"selection-probe","chapter":"The slow way","kind":"case-probe","eyebrow":"Find the rule","title":"When several tasks are ready, which one should run?","summary":"tasks = [\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\"], n = 2, so A is ready four times while B, C, and D appear once each.","workspacePanel":"visualizer","options":[{"id":"highest-count","label":"The ready task with the highest remaining count","rationale":"A runs four times and forces gaps after each run, so spending the gaps on A and saving the rare tasks for when A is cooling keeps the CPU busy. Run A first, then fill A's cooldown with B, C, and D.","isCorrect":true},{"id":"fewest-remaining","label":"The ready task with the fewest remaining runs","rationale":"Clearing the rare tasks first leaves A bunched up at the end, where every A run forces two idle intervals with nothing left to fill them.","isCorrect":false},{"id":"first-listed","label":"Whichever task appears first in the input order","rationale":"Input order has nothing to do with cooldown pressure; a task that runs once should not outrank the task that runs four times and dictates the gaps.","isCorrect":false}],"answer":"Run the ready task with the highest remaining count. The most frequent task creates the cooldown gaps, so spending intervals on it early and packing the rarer tasks into its gaps is what keeps the CPU from idling. That is exactly the choice a max-heap of counts makes for free.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"selection-heap","state":{"heap":{"values":[4,1,1,1],"name":"counts","current":0,"highlighted":[1,2]}}}]}},{"id":"greedy-safety","kind":"case-probe","chapter":"The idea","eyebrow":"Justify the pick","title":"Why is it safe to run the ready task with the largest remaining count?","summary":"A is ready with 4 copies left and B with 1, and a proposed schedule runs B now and delays A.","workspacePanel":"trace","options":[{"id":"swap-a-now","label":"Swap A into this interval and place B in a later open slot","rationale":"A has more future cooldown gaps to satisfy. Running it now cannot make B harder to place than A was.","isCorrect":true},{"id":"run-b-first","label":"Keep B first because it has fewer copies to finish","rationale":"Finishing a rare task early leaves the frequent task with more cooldown gaps still to create."},{"id":"idle-now","label":"Idle now so both tasks stay available later","rationale":"Idling while a task is ready only spends an interval without reducing any remaining count."}],"answer":"If a schedule chooses a smaller ready count before a larger one, swapping the larger task into that interval does not increase the number of cooldown gaps still needed."},{"id":"approach-selection","chapter":"The slow way","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"How should you find the most frequent ready task each interval?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"simulate-heap","name":"Heap simulation with cooldown","summary":"Count tasks, repeatedly pop the largest remaining count, and delay unfinished work in a cooldown queue.","decisionReason":"A heap hands back the most frequent ready task in log time, so each interval picks its task without re-reading every type.","complexity":{"time":"O(T log U)","space":"O(U)"},"tradeoffs":["Runs in O(T log U) time and uses O(U) space."],"isOptimal":true},{"id":"scan-each-time","name":"Scan every task type each interval","summary":"At every time step, search all task types for the best available task.","decisionReason":"This still returns the right schedule, but re-reading all U types every interval is the exact cost the cost probe already flagged.","complexity":{"time":"O(T * U)","space":"O(U)"},"tradeoffs":["Runs in O(T * U) time and uses O(U) space."],"isOptimal":false}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-heap","state":{"heap":{"values":[4,1],"name":"counts","current":0}}}]}},{"id":"heap-state","kind":"case-probe","chapter":"The idea","eyebrow":"Define the state","title":"At time t, which tasks belong in the heap?","summary":"A has just run and cannot run again until its cooldown expires.","workspacePanel":"trace","options":[{"id":"ready-only","label":"Only task counts that are ready at time t","rationale":"The heap top must be runnable now. Cooling tasks wait outside the heap until their ready time arrives.","isCorrect":true},{"id":"all-counts","label":"All remaining task counts, including cooling tasks","rationale":"Then the heap top could be a task that cannot legally run yet."},{"id":"cooling-only","label":"Only tasks whose cooldown has not expired","rationale":"Cooling tasks are precisely the ones the scheduler cannot choose yet."}],"answer":"The heap holds ready task counts only; a separate waiting area holds tasks until their cooldown expires."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Both counts sit in the heap, the largest on top","workspacePanel":"visualizer","body":["For tasks [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"] with n = 2, the counts are A = 3 and B = 3, and both go into the heap. A waiting area holds any task that just ran until its cooldown expires.","Each interval pops the largest ready count, runs that task, and parks it. When the heap is empty but the waiting area still holds work, the interval is idle and the clock still advances."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-heap","state":{"heap":{"values":[3,3],"name":"counts","current":0}}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the schedule","title":"Run the heap down to the final interval","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"run-first","state":{"heap":{"values":[3,3],"name":"counts","current":0,"highlighted":[1]}}},{"id":"empty-gap","state":{"heap":{"values":[],"name":"counts"}}},{"id":"finish","state":{"arrays":[{"name":"counts","values":[0,0],"current":0}]}}]},"beats":[{"id":"run-first","title":"Which task runs in interval 1, and what happens to it?","summary":"The heap holds counts A = 3 and B = 3, both ready.","prompt":"Both tasks tie for the top, and n = 2.","options":[{"id":"run-a-park","label":"A runs, drops to 2, and waits until interval 3 before it can run again","rationale":"A is one of the largest counts, so it pops first. After running it drops to 2 and goes into the waiting area with a ready time of 1 + 2 = 3, so B is free to run next.","isCorrect":true},{"id":"run-a-wait-four","label":"A runs, drops to 2, and waits until interval 4 before it can run again","rationale":"A ran at interval 1 with n = 2, so its next legal run is at 1 + 2 = 3, not 4. Waiting an extra interval would idle the CPU when A is already allowed back.","isCorrect":false},{"id":"run-both","label":"A and B both run during interval 1","rationale":"An interval runs at most one task, so A and B cannot share interval 1.","isCorrect":false}],"answer":"A pops and runs, drops to 2, and enters the waiting area until interval 3. The heap now holds only B = 3, which runs next in interval 2."},{"id":"empty-gap","title":"Interval 3 starts with an empty heap. What does the CPU do?","summary":"A ran in interval 1 and B in interval 2, so both are waiting out their cooldown and the heap is empty.","prompt":"A is not ready until interval 3 and B not until interval 4.","options":[{"id":"idle-then-a","label":"It idles for a moment, then A becomes ready and the interval runs A","rationale":"A reached its ready time of 3, so it re-enters the heap exactly at interval 3 and runs. The clock advances whether or not a task was waiting to fill the gap.","isCorrect":true},{"id":"skip-interval","label":"It skips interval 3 entirely and does not count it","rationale":"An idle interval still counts toward the total; the schedule cannot pretend a gap never happened.","isCorrect":false},{"id":"pull-b-early","label":"It pulls B back early since the heap is empty","rationale":"B is not ready until interval 4, and running it early would break its own cooldown; an empty heap waits rather than reaching past a ready time.","isCorrect":false}],"answer":"A reaches its ready time at interval 3 and rejoins the heap, so interval 3 runs A. Had no task been ready, the interval would still tick by as idle."},{"id":"finish","title":"After the heap and the waiting area are both empty, what is returned?","summary":"Both counts have reached zero, so no work is left in the heap or the waiting area.","prompt":"The schedule ran A, B, idle, A, B, idle, A, B. Count every interval, including the two idle ones.","options":[{"id":"eight","label":"8, the clock value when the last task runs","rationale":"Six task runs plus two idle intervals fill exactly eight slots, and the clock value at the end is the schedule length.","isCorrect":true},{"id":"six","label":"6, since there are six tasks","rationale":"Six is the task count, but the two forced idle intervals are real time slots and must be counted too.","isCorrect":false},{"id":"nine","label":"9, padding one extra idle interval at the end","rationale":"The schedule ends the moment the last task runs in interval 8; no trailing idle interval is needed once nothing is left.","isCorrect":false}],"answer":"The clock reads 8 when the last task runs and nothing remains in the heap or the waiting area, so the answer is 8: six task runs and two idle intervals."}]},{"id":"cooldown-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you push a run task straight back into the heap?","summary":"If the code skips the waiting area, it pops the largest count, runs it, and pushes unfinished work right back into the heap. The heap and the clock look correct. Watch what the schedule does on a single repeated task.","workspacePanel":"trace","pitfall":"The code below stores negated counts so the most frequent task pops first, then reinserts a task the moment it runs, with no cooldown delay. So the most frequent task is free to run in back-to-back intervals.","whyItMatters":"Two runs of the same task must be at least n intervals apart, but immediate reinsertion lets A run every interval. Park a task that just ran until time + n, and only then let it back into the heap.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    import heapq\n    counts: dict[str, int] = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n    heap: list[int] = []\n    for count in counts.values():\n        heapq.heappush(heap, -count)\n    time = 0\n    while heap:\n        time = time + 1\n        count = heapq.heappop(heap) + 1\n        if count < 0:\n            heapq.heappush(heap, count)\n    return time","steps":[{"id":"pf-setup","title":"tasks [\"A\",\"A\",\"A\"], n = 2 should take 7","codeLine":9,"summary":"A runs three times with a gap of two, so the only legal schedule is A, idle, idle, A, idle, idle, A, which is 7 intervals. The heap starts with the single count A = 3.","state":{"heap":{"values":[3],"name":"counts","current":0}}},{"id":"pf-run-1","title":"Interval 1 runs A, count drops to 2","codeLine":12,"summary":"A pops and runs, dropping to 2. With no waiting area, the leftover count is pushed straight back, so A is ready again immediately.","state":{"heap":{"values":[2],"name":"counts","current":0}}},{"id":"pf-run-2","title":"Interval 2 runs A again, back to back","codeLine":12,"summary":"A pops again in interval 2, only one interval after its last run. The required gap of two is already broken, but the heap has no idea.","state":{"heap":{"values":[1],"name":"counts","current":0}}},{"id":"pf-wrong","title":"It returns 3 instead of 7","codeLine":15,"summary":"A runs a third time in interval 3 and the heap empties, so the schedule reads A, A, A and the clock returns 3. The cooldown was never enforced, and the answer is far too small.","state":{"arrays":[{"name":"time","values":[3],"current":0}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task) : 0) + 1);\n}\nconst heap = new MinHeap();\nfor (const count of [...counts.values()]) {\n    heap.push(-count);\n}\nlet time = 0;\nwhile (heap.size() > 0) {\n    time = time + 1;\n    const count = heap.pop() + 1;\n    if (count < 0) {\n        heap.push(count);\n    }\n}\nreturn time;","lineMap":{"3":1,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":17},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"14":{"startLine":14,"endLine":16}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<string, number> = new Map();\nfor (const task of tasks) {\n    counts.set(task, (counts.has(task) ? counts.get(task)! : 0) + 1);\n}\nconst heap: MinHeap<number> = new MinHeap<number>();\nfor (const count of [...counts.values()]) {\n    heap.push(-count);\n}\nlet time = 0;\nwhile (heap.size() > 0) {\n    time = time + 1;\n    const count = heap.pop()! + 1;\n    if (count < 0) {\n        heap.push(count);\n    }\n}\nreturn time;","lineMap":{"3":1,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":17},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"14":{"startLine":14,"endLine":16}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<String, Integer> counts = new HashMap<String, Integer>();\nfor (String task : tasks) {\n    counts.put(task, (counts.getOrDefault(task, 0) + 1));\n}\nPriorityQueue<Integer> heap = new PriorityQueue<>();\nfor (Integer count : new ArrayList<Integer>(counts.values())) {\n    heap.offer(-count);\n}\nint time = 0;\nwhile (!heap.isEmpty()) {\n    time = time + 1;\n    int count = heap.poll() + 1;\n    if (count < 0) {\n        heap.offer(count);\n    }\n}\nreturn time;","lineMap":{"3":1,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":17},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"14":{"startLine":14,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<string, int> counts = new();\nforeach (string task in tasks) {\n    counts[task] = (counts.ContainsKey(task) ? counts[task] : 0) + 1;\n}\nPriorityQueue<int, int> heap = new();\nforeach (int count in counts.Values) {\n    heap.Enqueue(-count, -count);\n}\nint time = 0;\nwhile (heap.Count > 0) {\n    time = time + 1;\n    int count = heap.Dequeue() + 1;\n    if (count < 0) {\n        heap.Enqueue(count, count);\n    }\n}\nreturn time;","lineMap":{"3":1,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":17},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"14":{"startLine":14,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<string, int> counts;\nfor (string task : tasks) {\n    counts[task] += 1;\n}\nvector<int> heap;\nfor (const auto& [key, count] : counts) {\n    heap.push_back(-count); push_heap(heap.begin(), heap.end(), greater<>());\n}\nint time = 0;\nwhile (!heap.empty()) {\n    time = time + 1;\n    int count = heapPopValue(heap) + 1;\n    if (count < 0) {\n        heap.push_back(count); push_heap(heap.begin(), heap.end(), greater<>());\n    }\n}\nreturn time;","lineMap":{"3":1,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":17},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"14":{"startLine":14,"endLine":16}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could change the count?","summary":"The cooldown rule is only as safe as the inputs that press on its boundaries.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","body":["Two inputs press on the boundaries: a cooldown of zero, and one task that appears far more than the rest.","Does either one need handling the main loop does not already give it?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-zero","title":"No cooldown at all","summary":"tasks = [\"A\",\"A\",\"B\"], n = 0: the cooldown delay is zero.","state":{"heap":{"values":[2,1],"name":"counts","current":0}}},{"id":"edge-dominant","title":"One task dominates","summary":"tasks = [\"A\",\"A\",\"A\",\"A\",\"B\"], n = 2: A appears four times against a single B.","state":{"heap":{"values":[4,1],"name":"counts","current":0,"highlighted":[1]}}}]}},{"id":"zero-cooldown-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"With n = 0, how many intervals does the schedule take?","summary":"tasks = [\"A\",\"A\",\"B\"], n = 0, so a task may run again in the very next interval.","workspacePanel":"visualizer","options":[{"id":"three","label":"3, with no idle gaps","rationale":"A ready time of time + 0 means a task is ready again the next interval, so the heap is never empty while work remains and the CPU never idles. Three tasks take three intervals.","isCorrect":true},{"id":"five","label":"5, with idle gaps after the two A runs","rationale":"Idle gaps come from a positive cooldown; with n = 0 there is no delay, so no interval is wasted.","isCorrect":false},{"id":"two","label":"2, since only A and B are distinct","rationale":"The answer counts task runs, not distinct task types; A runs twice and B once, so three intervals pass.","isCorrect":false}],"answer":"It takes 3. A ready time of time + 0 puts a task back in play immediately, so the heap always has a task while work remains and the schedule is just the task count.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-result","state":{"arrays":[{"name":"time","values":[3],"current":0}]}}]}},{"id":"dominant-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"When the heap empties but A is still cooling, what does the CPU do?","summary":"tasks = [\"A\",\"A\",\"A\",\"A\",\"B\"], n = 2: after the early runs, A is waiting and nothing else is left to run.","workspacePanel":"visualizer","options":[{"id":"idle-tick","label":"It idles and the clock still advances until A is ready again","rationale":"A dominates, so once B is spent there is nothing to fill A's gaps. The interval idles, the clock ticks, and A re-enters the heap when its ready time arrives.","isCorrect":true},{"id":"stop-early","label":"It stops, since the heap is momentarily empty","rationale":"An empty heap does not mean the work is done; A is still waiting in cooldown, so stopping would leave runs unscheduled.","isCorrect":false},{"id":"run-a-early","label":"It runs A early to avoid wasting the interval","rationale":"Running A before its ready time breaks the cooldown; the gap has to be idle when nothing else is available.","isCorrect":false}],"answer":"It idles and the clock keeps advancing. The loop continues while either the heap or the waiting area holds work, so an empty heap with a task still cooling means work remains.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dominant-idle","state":{"heap":{"values":[],"name":"counts"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Build the heap-and-cooldown scheduler","summary":"Follow the heap and cooldown moves in order.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Count how often each task runs and load those counts into a max-heap. Then tick the clock one interval at a time: when a task is ready, run the most frequent one and hold it in a waiting area until its cooldown ends; when nothing is ready, let the interval idle. Keep going while the heap or the waiting area still holds work, and return the clock value at the end."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-heap","state":{"heap":{"values":[3,3],"name":"counts","current":0}}}]}},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the scheduler","summary":"Follow the heap and cooldown moves in order.","workspacePanel":"code","checkpoints":[{"id":"count-frequencies","title":"Count how often each task runs","description":"Walk the task list once and tally how many times each letter appears.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Counting distinct task names instead of their occurrences","Replacing a count instead of adding one to it"],"hint":"A dictionary keyed by the task letter holds each running tally.","semanticSpec":{"intent":"Build reusable frequency state for task counts.","doneWhen":"Each task occurrence increments the count for that task key.","mustProve":["A keyed counter is updated while scanning tasks."],"mustNotAccept":["A set of task names without counts."],"proofSnippets":[{"id":"py-task-scheduler-counts","language":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    counts = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n    return len(counts)"}],"roles":["task key","frequency map"]}},{"id":"seed-heap","title":"Load the counts into a max-heap","description":"Push every task count into a heap so the largest remaining count surfaces first.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"seed-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Pushing the task letters instead of their remaining counts","Ordering the heap so the smallest count comes out first"],"hint":"You want the largest count on top, so push the negated counts into a min-heap.","semanticSpec":{"intent":"Populate a heap from the frequency values.","doneWhen":"The heap receives the task-count values before the scheduling loop.","mustProve":["A priority storage is initialized and seeded from counted values."],"mustNotAccept":["Scheduling without a priority structure."],"proofSnippets":[{"id":"py-task-scheduler-seed-heap","language":"python","code":"def leastInterval(tasks: list[str], n: int) -> int:\n    counts = {}\n    for task in tasks:\n        counts[task] = counts.get(task, 0) + 1\n    heap = []\n    for count in counts.values():\n        heappush(heap, -count)\n    return len(heap)"}],"roles":["frequency values","priority heap"]}},{"id":"run-cycle","title":"Spend one interval per loop pass","description":"Advance the clock by one each pass and, when a task is ready, pop the most frequent one.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop","readMode":"heap-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]}]},"commonMistakes":["Running two tasks inside a single interval","Skipping the clock tick on an idle interval"],"hint":"Add one to the time on every pass, whether or not a task was available to run.","semanticSpec":{"intent":"Model each interval as one tick that may pop one heap task.","doneWhen":"The loop increments elapsed time and extracts from the heap when work is available.","mustProve":["A heap extract happens in a loop with elapsed time state."],"mustNotAccept":["A loop that never advances elapsed time."],"roles":["elapsed time","selected task count"]}},{"id":"cooldown-cycle","title":"Hold a run task until its cooldown ends","description":"Send a task that still has work left into a waiting area, and let it back into the heap only when its ready time arrives.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"uses_event_scheduled_selection","scope":"cooldown-cycle","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Pushing the task straight back into the heap while n is positive","Setting the ready time to time + n + 1 after the tick already counted this interval"],"hint":"After running a task at the current time, time + n is the earliest interval it may run again.","semanticSpec":{"intent":"Represent cooldown as delayed availability before heap selection resumes.","doneWhen":"The scheduler uses heap selection together with delayed availability state.","mustProve":["Priority selection is coupled to event-scheduled availability."],"mustNotAccept":["Immediate heap reinsertion with no cooldown state."],"roles":["ready time","cooldown queue","heap availability"]}},{"id":"return-time","title":"Return the elapsed intervals","description":"Once the heap and the waiting area are both empty, the clock value is the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the number of tasks rather than the number of intervals","Stopping while tasks are still waiting out their cooldown"],"hint":"The answer is the time accumulator after the last task has run and nothing is left waiting.","semanticSpec":{"intent":"Return the completed schedule length.","doneWhen":"The returned value is the terminal elapsed-time state.","mustProve":["A numeric state updated by the loop is returned."],"mustNotAccept":["Returning the heap size or frequency map size."],"roles":["elapsed time","answer"]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Count the tasks, run the most frequent ready one, hold it through its cooldown, and count every interval.","body":["Task Scheduler is a simulation that only ever needs one thing fast each interval: the most frequent task that is ready to run. A max-heap of counts hands that over on demand, and a waiting area keyed by ready time enforces the cooldown.","When the heap empties while a task is still cooling, the interval idles and the clock still advances, because an idle slot is real time spent.","Each interval pops and may re-push one count along a single root-to-leaf path, and there are O(T) intervals over U distinct tasks, so the simulation is O(T log U), down from the O(T x U) of scanning every task type each interval."],"takeaways":[{"title":"Reach for a heap when you keep needing the maximum","body":"Each interval asks for the most frequent ready task, and a heap surfaces it in log time instead of scanning every task type."},{"title":"Cooldown means delayed availability","body":"Park a task that just ran until time + n and let it back into the heap then, so two runs of the same task stay at least n intervals apart."},{"title":"Idle intervals are real time","body":"When the heap is empty but work is still cooling down, the clock advances on an idle interval, so the loop runs while either the heap or the waiting area holds work."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote.","workspacePanel":"code"}],"slidesOrigin":"authored"}}
