KatInterview

Peak Concurrent Tasks: Minimum Workers Needed

Greedy & IntervalsAuto-graded · 18 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingheap

Last updated

Tests interval overlap detection using sweep-line or heap techniques to find the maximum number of simultaneously active tasks.

Problem

You manage a pipeline of tasks, each defined by a start time and a finish time. A worker can only handle one task at a time, but as soon as a task finishes at time T, that same worker is immediately available to pick up a new task starting at time T.

Given a list of tasks where tasks[i] = [start, finish] describes when task i begins and ends (start < finish), return the minimum number of workers required so that every task runs without delay.

Constraints

  • 1 <= len(tasks) <= 10^5
  • tasks[i].length == 2
  • 0 <= tasks[i][0] < tasks[i][1] <= 10^9

Notes

  • A worker finishing at time T is available for a task starting at time T — back-to-back assignments do not conflict.
  • Tasks may be given in any order.
  • Fully nested tasks (e.g., one task entirely contained within another's window) each require their own worker.

Examples

Example 1

Input: min_workers_needed([[0, 30], [5, 10], [15, 20]])

Output: 2

Example 2

Input: min_workers_needed([[7, 10], [2, 4]])

Output: 1

Hints

Hint 1

The minimum number of workers equals the maximum number of tasks that are simultaneously in progress at any single moment in time. Try to find that peak overlap count.

Hint 2

Sort the start times and end times into two separate arrays. Use two pointers to walk through them in tandem: each unmatched start increments a counter, and each end that arrives before or at the next start decrements it.

Hint 3

If you prefer a heap approach, sort tasks by start time and maintain a min-heap of finish times — one entry per busy worker. Before assigning the next task, check whether the earliest-finishing worker is already free (heap top <= current start). The key tie-break: use <= not <, because a worker finishing at T can start a new task at T.