{"id":10087,"date":"2025-09-19T21:02:37","date_gmt":"2025-09-19T15:32:37","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10087"},"modified":"2025-09-19T21:04:39","modified_gmt":"2025-09-19T15:34:39","slug":"task-scheduler","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/task-scheduler\/","title":{"rendered":"Task Scheduler"},"content":{"rendered":"\n\n\n<!-- merge_7-->\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        You are given an array of CPU <code>tasks<\/code>, each labeled with a letter from A to Z, and a number <code>n<\/code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#8217;s a constraint: there has to be a gap of at <strong>least<\/strong> <code>n<\/code> intervals between two tasks with the same label.\n    <\/p>\n\n    <p>Return the <strong>minimum<\/strong> number of CPU intervals required to complete all tasks.<\/p>\n    \n    <h3>Example 1:<\/h2>\n    <p><strong>Input:<\/strong> tasks = [&#8220;A&#8221;,&#8221;A&#8221;,&#8221;A&#8221;,&#8221;B&#8221;,&#8221;B&#8221;,&#8221;B&#8221;], n = 2\n<\/p>\n    <p><strong>Output:<\/strong> 8<\/p>\n    <p><strong>Explanation:<\/strong>\n        A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.\n        After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can do A again as 2 intervals have passed.\n    <\/p>\n\n    <h3>Example 2:<\/h3>\n    <p><strong>Input: <\/strong>[&#8220;A&#8221;,&#8221;C&#8221;,&#8221;A&#8221;,&#8221;B&#8221;,&#8221;D&#8221;,&#8221;B&#8221;], n = 1<\/p>\n    <p><strong>Output: <\/strong>6<\/p>\n    <p><strong>Explanation: <\/strong> A possible sequence is: A -> B -> C -> D -> A -> B. With a cooling interval of 1, you can repeat a task after just one other task.<\/p>\n\n    <h3>Example 3:<\/h3>\n    <p><strong>Input: <\/strong>tasks = [&#8220;A&#8221;,&#8221;A&#8221;,&#8221;A&#8221;, &#8220;B&#8221;,&#8221;B&#8221;,&#8221;B&#8221;], n = 3<\/p>\n    <p><strong>Output: <\/strong>10<\/p>\n    <p><strong>Explanation: <\/strong>\n        A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.\n        There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.\n    <\/p>\n\n    <h3>Constraints<\/h3>\n    <ul>\n        <li><code>1 <= tasks.length <= 10<sup>4<\/sup><\/code><\/li>\n        <li><code>tasks[i]<\/code> is an uppercase English letter.<\/li>\n        <li><code>0 <= n <= 100<\/code><\/li>\n    <\/ul>\n<h2>Approach:<\/h2>\n   <ul>\n       <li>Count frequency of each task (A\u2013Z).<\/li>\n       <li>Find the maximum frequency <code>(maxFreq)<\/code> \u2014 the most repeated task.<\/li>\n       <li>Count how many tasks have this maximum frequency (countOfMaxFreqCharacters).<\/li>\n       <li>Compute the ideal cycles needed to schedule these most frequent tasks with cooldowns:\n\n            <strong>(n+1)\u00d7(maxFreq\u22121)+countOfMaxFreqCharacters<\/strong>\n        <ul>\n            <li><code>(n+1)<\/code> \u2192 each group of task + cooldown.<\/li>\n            <li><code>(maxFreq - 1)<\/code> \u2192 groups formed except last one.<\/li>\n            <li><code>countOfMaxFreqCharacters<\/code> \u2192 handles ties of max frequency tasks<\/li>\n        <\/ul>\n       <\/li>\n       <li>The result is the maximum of:\n        <ul>\n            <li><code>arr.length<\/code> (if enough tasks to fill gaps)<\/li>\n            <li><code>cycles<\/code> (if idle slots are unavoidable)<\/li>\n        <\/ul>\n       <\/li>\n    <\/ul>\n\n    <h2>Time & Space Complexity:<\/h2>\n    <p><strong>Time Complexity:<\/strong> <code>O(arr.length)<\/code><\/p>\n    <p><strong>Space Complexity:<\/strong> <code>O(1)<\/code><\/p>\n\n<h2>Dry Run<\/h2> <div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> <p><strong>Input:<\/strong> <code>arr = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2<\/code><\/p> <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\"> Step 0: Start Function: leastInterval(arr, n) arr = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2 freq = Array(26).fill(0) \/\/ all zeros maxFreq = 0\nStep 1: Build frequency table and track maxFreq\ni = 0, arr[0] = \"A\" -> curr = \"A\".charCodeAt() - 65 = 0\n++freq[0] => freq['A'] = 1\nmaxFreq = max(0,1) = 1\ni = 1, arr[1] = \"A\"\n++freq[0] => freq['A'] = 2\nmaxFreq = max(1,2) = 2\ni = 2, arr[2] = \"A\"\n++freq[0] => freq['A'] = 3\nmaxFreq = max(2,3) = 3\ni = 3, arr[3] = \"B\" -> curr = 1\n++freq[1] => freq['B'] = 1\nmaxFreq = max(3,1) = 3\ni = 4, arr[4] = \"B\"\n++freq[1] => freq['B'] = 2\nmaxFreq = max(3,2) = 3\ni = 5, arr[5] = \"B\"\n++freq[1] => freq['B'] = 3\nmaxFreq = max(3,3) = 3\nAfter loop:\nfreq['A'] = 3, freq['B'] = 3, all others = 0\nmaxFreq = 3\nStep 2: Count how many characters have frequency == maxFreq\ncountOfMaxFreqCharacters = 0\nfor i from 0..25:\nwhen i=0 (A): freq[0] === 3 -> ++countOfMaxFreqCharacters => 1\nwhen i=1 (B): freq[1] === 3 -> ++countOfMaxFreqCharacters => 2\nothers: freq != 3\nFinal countOfMaxFreqCharacters = 2\nStep 3: Compute cycles (minimum length by the formula)\ncycles = ((n + 1) * (maxFreq - 1)) + countOfMaxFreqCharacters\n= ((2 + 1) * (3 - 1)) + 2\n= (3 * 2) + 2\n= 6 + 2\n= 8\nStep 4: Final result is max(arr.length, cycles)\narr.length = 6\ncycles = 8\nreturn Math.max(6, 8) => 8\nStep 5: End\nFinal returned value = 8\n<\/pre>\n<p><strong>Output:<\/strong> <code>8<\/code><\/p> <\/div>\n<\/div>\n\n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\nvar leastInterval = function(tasks, n) {\n    let freq = Array(26).fill(0);\n    let maxFreq = 0;\n\n    for (let i = 0; i < tasks.length; i++) {\n        let curr = tasks[i].charCodeAt() - 65;  \/\/ Map 'A'-'Z' to 0-25\n        freq[curr]++;\n        maxFreq = Math.max(maxFreq, freq[curr]);\n    }\n    let countMaxFreq = 0;\n    for (let i = 0; i < 26; i++) {\n        if (freq[i] === maxFreq) {\n            countMaxFreq++;\n        }\n    }\n    let cycles = (maxFreq - 1) * (n + 1) + countMaxFreq;\n    return Math.max(tasks.length, cycles);\n};\n\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\ndef leastInterval(tasks, n):\n    freq = [0] * 26\n    maxFreq = 0\n    for t in tasks:\n        c = t[0]  # in case it's a string\n        idx = ord(c) - ord('A')\n        freq[idx] += 1\n        if freq[idx] > maxFreq:\n            maxFreq = freq[idx]\n\n    countOfMax = sum(1 for f in freq if f == maxFreq)\n    cycles = (n + 1) * (maxFreq - 1) + countOfMax\n    return max(len(tasks), cycles)\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\nimport java.util.*;\npublic class Main {\n    public static int leastInterval(char[] tasks, int n) {\n        int[] freq = new int[26];\n        int maxFreq = 0;\n        for (char c : tasks) {\n            int idx = c - 'A';\n            freq[idx]++;\n            if (freq[idx] > maxFreq) maxFreq = freq[idx];\n        }\n        int countOfMax = 0;\n        for (int f : freq) if (f == maxFreq) countOfMax++;\n        int cycles = (n + 1) * (maxFreq - 1) + countOfMax;\n        return Math.max(tasks.length, cycles);\n    }\n    public static void main(String[] args) {\n        char[] tasks = {'A','A','A','B','B','B'};\n        int n = 2;\n        System.out.println(leastInterval(tasks, n)); \/\/ expected 8\n    }\n}\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n<!-- #include &lt;vector&gt; -->\n#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint leastInterval(const vector<char>& tasks, int n) {\n    vector<int> freq(26, 0);\n    int maxFreq = 0;\n    for(char c : tasks) {\n        int idx = c - 'A';\n        ++freq[idx];\n        maxFreq = max(maxFreq, freq[idx]);\n    }\n    int countOfMax = 0;\n    for(int f : freq) if(f == maxFreq) ++countOfMax;\n\n    int cycles = (n + 1) * (maxFreq - 1) + countOfMax;\n    return max((int)tasks.size(), cycles);\n}\nint main() {\n    vector<char> tasks = {'A','A','A','B','B','B'};\n    int n = 2;\n    cout << leastInterval(tasks, n) << endl; \/\/ expected 8\n    return 0;\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\nint leastInterval(char tasks[][2], int tasksSize, int n) {\n    int freq[26];\n    for(int i=0;i<26;i++) freq[i]=0;\n    int maxFreq = 0;\n    for(int i=0;i<tasksSize;i++){\n        char c = tasks[i][0]; \/\/ tasks as array of 1-char strings\n        int idx = c - 'A';\n        ++freq[idx];\n        if(freq[idx] > maxFreq) maxFreq = freq[idx];\n    }\n    int countOfMax = 0;\n    for(int i=0;i<26;i++) if(freq[i] == maxFreq) ++countOfMax;\n    int cycles = (n + 1) * (maxFreq - 1) + countOfMax;\n    return (tasksSize > cycles) ? tasksSize : cycles;\n}\nint main() {\n    char tasks[][2] = {\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"};\n    int size = sizeof(tasks) \/ sizeof(tasks[0]);\n    int n = 2;\n    printf(\"%d\\n\", leastInterval(tasks, size, n)); \n    return 0;\n}\n <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\nclass Program {\n    static int LeastInterval(char[] tasks, int n) {\n        int[] freq = new int[26];\n        int maxFreq = 0;\n        foreach(char c in tasks) {\n            int idx = c - 'A';\n            freq[idx]++;\n            if (freq[idx] > maxFreq) maxFreq = freq[idx];\n        }\n        int countOfMax = 0;\n        foreach(int f in freq) if (f == maxFreq) countOfMax++;\n\n        int cycles = (n + 1) * (maxFreq - 1) + countOfMax;\n        return Math.Max(tasks.Length, cycles);\n    }\n    static void Main() {\n        char[] tasks = new char[] {'A','A','A','B','B','B'};\n        int n = 2;\n        Console.WriteLine(LeastInterval(tasks, n)); \/\/ expected 8\n    }\n}\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#8217;s a constraint: there has to be a gap of<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-10087","post","type-post","status-publish","format-standard","category-algorithms","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10087","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10087"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10087\/revisions"}],"predecessor-version":[{"id":10088,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10087\/revisions\/10088"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10087"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10087"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10087"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}