Minimum Shift Count for Concurrent Task Scheduling
Greedy & IntervalsModel answerLast updated
Given tasks with time windows and resource demands, find the fewest parallel workers needed so no worker exceeds capacity K at any moment.
Background
You run an operations platform that assigns jobs to workers. Each job runs during a specific time window and consumes some amount of a shared resource while active. A worker can hold multiple jobs simultaneously, but the combined resource usage across all active jobs on that worker must never exceed a fixed limit at any point in time. Jobs that do not overlap can be assigned to the same worker back-to-back.
Your goal is to figure out how few workers you need to cover every job.
Task
Write a function that, given a list of jobs and a per-worker capacity limit, returns the minimum number of workers required.
Each job is described by three integers: [start, end, demand], where the job is active during the half-open interval [start, end) — a job ending at time t frees its demand before a new job starting at t begins. The demand represents how much of the worker's capacity that job consumes while active.
def min_workers(jobs: List[List[int]], K: int) -> int
Constraints
1 <= len(jobs) <= 10^40 <= start < end <= 10^61 <= demand <= K1 <= K <= 100
Examples
Example 1
jobs = [[1, 5, 2], [2, 6, 2], [7, 8, 1]], K = 3
Output: 2
Jobs [1,5,2] and [2,6,2] overlap during [2,5) and have a combined demand of 4, which exceeds K=3. They must go to separate workers. Job [7,8,1] does not overlap either of the first two, so it can share a worker with one of them — no third worker is needed.
Example 2
jobs = [[0, 10, 3], [0, 10, 3], [0, 10, 3]], K = 3
Output: 3
All three jobs span the exact same window. Each fills a worker entirely. Three workers are required.
Example 3
jobs = [[1, 3, 1], [3, 5, 1], [1, 5, 1]], K = 2
Output: 2
Jobs [1,3,1] and [3,5,1] do not overlap (half-open intervals) so they fit the same worker back-to-back. Job [1,5,1] overlaps both, and combined demand with either active segment is 2 which equals K, so it can share with the first worker. Output is 1... wait, check carefully: at t=1, worker A carries [1,3,1] (demand 1) and [1,5,1] (demand 1) — total 2 = K. At t=3, [1,3,1] ends, then [3,5,1] starts on worker A — total still 2 = K. All three jobs fit on one worker. Output: 1.
What to return
Return a single integer: the minimum number of workers.
Edge Cases to Consider
- A single job always needs exactly one worker.
- Jobs whose windows share only an endpoint (e.g.,
[1,5)and[5,9)) do not overlap, so they can share a worker. - A job with
demand == Kfills a worker entirely while active but that worker is reusable afterward. - All jobs sharing the same window turns this into pure bin packing.
Hints
Hint 1
Sort jobs by start time. Among jobs starting at the same time, process higher-demand jobs first — this mirrors the 'first-fit decreasing' strategy from bin packing and tends to leave smaller gaps for later jobs.
Hint 2
Use a min-heap keyed on end time to track active jobs per worker. Before assigning a new job starting at time s, pop all heap entries with end <= s and subtract their demand from the corresponding worker's current load. A job ending at exactly s does not conflict with one starting at s.
Hint 3
With K <= 100, you can keep an array of sets indexed by current load level (0 through K). To find the best-fit worker for a job with demand c, scan from load level K-c down to 0 and pick any worker in the first non-empty bucket. This gives O(K) lookup per job without scanning all workers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Reading the Problem Carefully
Before writing any code, run the first example by hand. Job [7,8,1] does not overlap the other two, yet the answer is 2, not 3. That tells you a worker is not a single frozen time slot — a worker persists across the full timeline and can take on sequential jobs as long as the total active demand never exceeds K at any moment.
Also pin down the interval semantics: the problem uses half-open intervals [start, end). A job ending at time 5 and a job starting at time 5 do not coexist, so they can share a worker. State this assumption explicitly in an interview; interviewers want to see you handle boundary conditions deliberately.
Why This Is Hard in General
When every job spans the same window, this reduces exactly to bin packing — pack demands into bins of size K. Bin packing is NP-hard, so there is no known polynomial exact algorithm for arbitrary inputs. A strong answer acknowledges this rather than claiming the greedy is globally optimal. The greedy below is the standard production-grade approach and is optimal in two important special cases: when all demands are equal (classic interval partitioning), and when windows vary but demands are uniform.
The Algorithm
Step 1 — Sort. Order jobs by (start, -demand). Processing higher-demand jobs first among ties is the "first-fit decreasing" heuristic: large items are harder to place, so settling them early leaves more flexibility for small ones.
Step 2 — Sweep. Process jobs left to right in time. Maintain each worker's current load — the sum of demands of jobs currently active on that worker.
Step 3 — Release finished jobs. Before placing a job starting at time s, use a min-heap keyed on end time to find all jobs that finished at or before s. Subtract each one's demand from its worker's load. The half-open convention means end <= s triggers release.
Step 4 — Best-fit placement. Assign the new job to the worker with the highest current load that can still absorb demand c (i.e., load + c <= K). This "best fit" strategy keeps workers as full as possible, maximizing reuse.
Step 5 — O(K) lookup via load buckets. Since K ≤ 100, maintain an array buckets where buckets[L] is the set of workers whose current load is exactly L. To find the best fit for demand c, scan from L = K - c down to 0 and pick any worker in the first non-empty bucket. This is O(K) per job, independent of the number of workers.
Why Checking Load at Start Time Is Sufficient
This is the key correctness argument. When you assign job [s, e) with demand c to a worker, every job already on that worker that is still active at time s has a start time ≤ s. Any such job active at some later time t ∈ [s, e) was also active at s. So the worker's load at s is an upper bound on its load throughout [s, e). If load[s] + c ≤ K, the constraint holds for the entire new job's duration. Future jobs placed on the same worker are checked by the same logic, so no time point ever violates K.
Complexity
- Time: O(n log n) for sorting and heap operations, plus O(n · K) for bucket scans. With n = 10^4 and K = 100 that is roughly 10^6 operations — well within budget.
- Space: O(n) for the heap, per-worker loads, and buckets.
Python Implementation
import heapq
from typing import List
def min_workers(jobs: List[List[int]], K: int) -> int:
# Sort by start time; break ties by placing higher-demand jobs first.
ordered = sorted(jobs, key=lambda j: (j[0], -j[2]))
load: List[int] = [] # load[w] = current demand on worker w
buckets: List[set] = [set() for _ in range(K + 1)] # buckets[L] = workers with load == L
heap: List[tuple] = [] # min-heap of (end_time, worker, demand)
def move(w: int, new_load: int) -> None:
"""Update worker w's load and reindex its bucket."""
buckets[load[w]].discard(w)
load[w] = new_load
buckets[new_load].add(w)
for s, e, c in ordered:
# Release jobs that finished at or before start time s (half-open intervals).
while heap and heap[0][0] <= s:
end_t, w, dem = heapq.heappop(heap)
move(w, load[w] - dem)
# Find the most-loaded worker that can still accept demand c.
best = -1
for L in range(K - c, -1, -1):
if buckets[L]:
best = next(iter(buckets[L]))
break
if best == -1: # No existing worker fits; open a new one.
best = len(load)
load.append(0)
buckets[0].add(best)
move(best, load[best] + c)
heapq.heappush(heap, (e, best, c))
return len(load)
Trace of Example 1 (K = 3)
| Event | Action | Workers |
|---|---|---|
Job [1,5,2] | Open worker 0, load → 2 | W0: load 2 |
Job [2,6,2] | No worker has load ≤ 1; open worker 1 | W0: 2, W1: 2 |
Job [7,8,1] | Both jobs ended (end ≤ 7); loads reset to 0. Best fit: W0 or W1 | W0: 1, W1: 0 |
Result: 2 workers.
Common Mistakes
- Treating intervals as closed. Using
end < sinstead ofend <= scauses jobs ending exactly atsto still appear active, forcing unnecessary extra workers on touching intervals. - Claiming the greedy is optimal. It is not optimal in general due to the bin-packing core. Saying so shows you understand the hardness boundary.
- Scanning all workers for best fit. With many workers this becomes O(n²). The bucket array makes it O(K) per job.
- Ignoring start-time ties. Not sorting by
-demandwithin the same start time leads to suboptimal packing and a higher worker count than necessary.
Follow-Up: Adding a Location Constraint
If workers also have a maximum route distance, compatibility becomes spatial as well as temporal. A practical approach: partition jobs by geographic region (e.g., geohash or H3 cells), run the same sweep within each partition, and add a detour-feasibility check when inserting a job onto an existing worker's route. At scale this becomes a vehicle routing problem with time windows (VRPTW), typically solved with metaheuristics or constraint solvers such as OR-Tools rather than exact methods.