DSA Heaps

Schedule Tasks on Minimum Machines

curriculum variant of meeting rooms — schedule interval-style tasks across the fewest possible machines.

Medium
Time O(n log n) Space O(n)
4 min read
heaps intervals

Problem#

(curriculum variant.) Given a list of tasks, each with (start, end), return the minimum number of machines needed to run all tasks without overlap on any machine.

Examples#

  • [(1,4),(2,3),(3,5)]2

Constraints#

  • 1 <= n <= 10^5.

Approach#

Identical to Meeting Rooms II: sort by start, maintain a min-heap of end times of in-use machines. For each task, pop the heap top if it ≤ task start (machine free), else add a new machine.

Solution#

Schedule Tasks on Minimum Machines
int minMachines(vector<pair<int,int>>& tasks) {
sort(tasks.begin(), tasks.end());
priority_queue<int, vector<int>, greater<int>> ends;
for (auto& [s, e] : tasks) {
if (!ends.empty() && ends.top() <= s) ends.pop();
ends.push(e);
}
return ends.size();
}

Editorial#

Identical structure to Meeting Rooms II — “machines” and “rooms” are interchangeable resources for non-overlapping interval scheduling. The heap’s size is the peak concurrency, which is the answer.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.