মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 6 · Heaps / Priority Queues

6.4 Heap + Greedy Scheduling

চিনবেন কীভাবে
"task scheduler with cooldown", "reorganize so no two same are adjacent", "minimum refuelling stops", "maximize with limited capacity" — greedy choice of the best available option, and the heap is what makes "best available" cheap
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Task SchedulerLC 621 (Medium — Meta/Amazon High)

Statement (Demo): Given CPU tasks (letters) and a cooldown n, the same task must be at least n slots apart; idle slots are allowed. Return the minimum number of slots needed to run every task. Example: tasks=["A","A","A","B","B","B"], n=28 (A B idle A B idle A B) | ⚡ tasks.length ≤ 10⁴, 0 ≤ n ≤ 100

Approach: Greedy: in every cycle of n + 1 slots, run the tasks with the most remaining copies first. A max-heap of counts gives them in order; tasks that still have copies go back after the cycle. If the heap empties mid-cycle, the last cycle needs no idle padding. (MinHeap → 6.1.)

function leastInterval(tasks, n) {
  const counts = new Map();
  for (const t of tasks) counts.set(t, (counts.get(t) || 0) + 1);
  const heap = new MinHeap((a, b) => b - a); // max-heap of remaining counts
  for (const c of counts.values()) heap.push(c);
  let time = 0;
  while (heap.size) {
    const waiting = [];
    let slots = 0;
    for (; slots <= n && heap.size; slots++) {
      const c = heap.pop(); // most copies left runs first
      if (c > 1) waiting.push(c - 1);
    }
    for (const c of waiting) heap.push(c);
    time += heap.size ? n + 1 : slots; // last cycle: no idle tail
  }
  return time;
}

Complexity: Time O(T log 26) ≈ O(T), Space O(26) (the counting formula (maxCount-1)*(n+1)+ties is O(T) — explain it as the follow-up)

Demo · Task Schedulerplan · দিন ০৬৭LC 621
নোট · ফাঁকা

প্রবলেম

  • Reorganize Stringplan · দিন ০৬৮🔥 Must-doLC 767
    (always place the most frequent letter that differs from the previous one)

    Statement: Given a string s, rearrange it so no two adjacent characters are equal. Return any valid arrangement, or "" if impossible.
    Example: s="aab""aba"; s="aaab""" | ⚡ len ≤ 500

    নোট · ফাঁকা
  • Minimum Number of Refueling Stopsplan · দিন ০৭১🔥 Must-doLC 871
    (Hard — Google High; pass stations, keep their fuel in a max-heap, refuel only when stuck)

    Statement: A car starts with startFuel and must travel target miles. stations[i] = [position, fuel]. Return the fewest stops needed to reach the target, or -1.
    Example: target=100, startFuel=10, stations=[[10,60],[20,30],[30,30],[60,40]]2 | ⚡ stations.length ≤ 500

    নোট · ফাঁকা
আরও দেখুন
Greedy without a heap (activity selection, candy) → see 10.1