Minimum Servers for Concurrent Tasks
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a collection of scheduled jobs intervals, where each element [start, end] specifies a half-open execution window [start, end), compute the fewest homogeneous worker machines required so every job runs without conflict:
def minimum_servers(intervals: List[List[int]]) -> int:
A machine can execute at most one job at any moment in time:
- Two windows
[a_start, a_end)and[b_start, b_end)conflict whenever they share at least one timestamp (a_start < b_endandb_start < a_end). - Because the upper endpoint is excluded, a job finishing at timestamp
t([a, t)) releases its machine immediately for a job beginning at timestampt([t, b)). - If
intervalscontains zero jobs, return0.
Your implementation must run in O(n log n) time for n = len(intervals).
Examples
Example 1
Input: intervals = [[2, 6], [4, 9], [10, 13]]
Output: 2
Walk-through: [2, 6) and [4, 9) are both active throughout [4, 6), forcing 2 machines. Once [2, 6) completes at timestamp 6, that first machine is idle well before [10, 13) begins.
Example 2
Input: intervals = [[0, 4], [4, 7], [7, 11]]
Output: 1
Walk-through: [0, 4) hands off to [4, 7) at timestamp 4, which then hands off to [7, 11) at timestamp 7. Since half-open endpoints never collide at boundary timestamps, a single machine executes all three jobs back to back.
Example 3
Input: intervals = [[3, 8], [3, 8], [3, 8], [8, 12], [5, 8]]
Output: 4
Walk-through: During [5, 8), all three [3, 8) jobs plus [5, 8) execute concurrently, requiring 4 distinct machines. At timestamp 8, those 4 machines finish and [8, 12) reuses one of them without increasing the total count.
Constraints
0 <= len(intervals) <= 10^5- Every entry has length 2 with integer timestamps satisfying
0 <= start < end <= 10^9. - Input intervals may arrive in arbitrary order and may contain duplicate windows.
Step-by-step walkthrough
Understand half-open intervals and overlap
We receive
njobs, each written as[start, end)— a half-open interval coveringstartand every moment up to, but excluding,end(start < end). Conflicting jobs cannot share a machine, and we want the smallest pool of machines capable of running every job (returning0whenintervalsis empty).Because
endis excluded, a job finishing at timestamptand another starting at timestamptnever run simultaneously and can share one server:Time: 0 2 4 6 8 9 10 11 13 Example 1: [=======) [===========) [=======) Conflicts on [4, 6) -> needs 2 servers Example 2: [=======)[=====)[========) 0 4 7 11 Handoffs at 4 and 7 without overlap -> needs 1 serverWhy peak concurrency is the bottleneck
Suppose at some instant
t,kjobs are all running simultaneously. Every pair among thosekjobs overlaps att, so allkof them must occupy distinct servers. Thus, any valid schedule needs at least as many servers as the peak number of simultaneously active jobs.A brute-force check inspects each job's
starttimestamp and scans allnjobs to count how many satisfys <= start < e. That finds the exact peak — since active concurrency only rises when a job begins — but scanningnjobs for each of thenstart timestamps costsO(n^2)time, which times out atn = 100,000. We wantO(n log n)time with a constructive server assignment.Key idea: sort by start time and track servers in a min-heap
Simulate dispatching jobs in chronological start order:
- Sort
intervalsfrom earlieststartto lateststart. - Maintain a min-heap
free_timesstoring one entry per allocated server: the timestamp when its current job finishes. Becausefree_timesis a min-heap,free_times[0]is always the earliest timestamp any allocated server becomes free.
When the next job
[start, end)arrives:- If
free_times[0] <= start: the earliest-finishing server has already completed its prior job! Pop that old end timestamp and reuse the server by pushingend. - Otherwise (
free_timesis empty orfree_times[0] > start): even the earliest-finishing server remains busy paststart, meaning every allocated server is currently occupied. Pushendwithout popping — opening one brand-new server.
Why can no schedule ever use fewer servers? Consider the moment we open our very last server (server
#k, for a job starting ats). Because we visit jobs in non-decreasing start order, allk - 1existing servers are running jobs that started<= s. And becausefree_times[0] > s, allk - 1of those jobs finish strictly afters. Including the new job,kjobs are simultaneously active at timestamps— provingkservers are strictly required!- Sort
Two subtle boundary rules: `<=` and popping at most once
Before coding the loop, nail down two critical details:
- Use
free_times[0] <= start, not<: Under half-open windows, a server whose previous job ended at4is immediately free at4to run[4, 7). Writing<would needlessly open a second server on Example 2. - Use
if, notwhile, when popping: Suppose two servers finished at2and the next job is[5, 6). Our single incoming job occupies only one idle server; the second server remains idle infree_times(with free time2) ready for later jobs. Popping at most one entry preserves one heap entry per allocated server, solen(free_times)at termination equals the exact server count!
def minimum_servers(intervals: List[List[int]]) -> int: if not intervals: return 0 # Phase 1: Sort tasks chronologically by start time (ties broken by end time). sorted_tasks = sorted(intervals) # free_times: min-heap of [server_free_time], with ONE entry per allocated server. # Example: [4, 5] means 2 servers exist; the earliest-finishing one frees up at time 4. free_times: List[int] = [] # Phase 2: Assign each task to an already-free server if possible, else open a new one. for start, end in sorted_tasks: # Half-open intervals [a, t) and [t, b) do not overlap, so '<=' allows instant reuse. # Pop at most ONE free server so len(free_times) always equals total servers opened. if free_times and free_times[0] <= start: heapq.heappop(free_times) # Record when the server running this task will become free again. heapq.heappush(free_times, end) return len(free_times)- Use
Trace Example 1 and Example 3 step by step
Example 1: intervals = [[2, 6], [4, 9], [10, 13]] Task [2, 6): free_times is [] -> open server 1 -> free_times = [6] Task [4, 9): earliest free is 6 > 4 -> open server 2 -> free_times = [6, 9] Task [10, 13): earliest free is 6 <= 10 -> pop 6, push 13 -> free_times = [9, 13] Result: len(free_times) = 2 Example 3: intervals = [[3, 8], [3, 8], [3, 8], [8, 12], [5, 8]] Sorted: [[3, 8], [3, 8], [3, 8], [5, 8], [8, 12]] Task [3, 8): free_times is [] -> open server 1 -> free_times = [8] Task [3, 8): earliest free is 8 > 3 -> open server 2 -> free_times = [8, 8] Task [3, 8): earliest free is 8 > 3 -> open server 3 -> free_times = [8, 8, 8] Task [5, 8): earliest free is 8 > 5 -> open server 4 -> free_times = [8, 8, 8, 8] Task [8, 12): earliest free is 8 <= 8 -> pop one 8, push 12 -> free_times = [8, 8, 8, 12] Result: len(free_times) = 4Notice the last step of Example 3: all four servers became free at
8,[8, 12)claimed one of them, and the other three stayed infree_timesso the total server count remained4.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def minimum_servers(intervals: List[List[int]]) -> int: if not intervals: return 0 # Phase 1: Sort tasks chronologically by start time (ties broken by end time). sorted_tasks = sorted(intervals) # free_times: min-heap of [server_free_time], with ONE entry per allocated server. # Example: [4, 5] means 2 servers exist; the earliest-finishing one frees up at time 4. free_times: List[int] = [] # Phase 2: Assign each task to an already-free server if possible, else open a new one. for start, end in sorted_tasks: # Half-open intervals [a, t) and [t, b) do not overlap, so '<=' allows instant reuse. # Pop at most ONE free server so len(free_times) always equals total servers opened. if free_times and free_times[0] <= start: heapq.heappop(free_times) # Record when the server running this task will become free again. heapq.heappush(free_times, end) return len(free_times)✅ Submit now — all tests should pass.
Intuition & how it works
Picture handing out bowling lanes to groups arriving across the afternoon, where each reservation [start, end) is a half-open interval — a window that includes start up to, but excluding, end (so a party finishing at 4:00 PM vacates its lane right in time for a 4:00 PM check-in). When we process reservations in chronological start order, we only ever need to inspect the single lane whose current game ends earliest: if even that lane is still occupied when the next group walks in, every other active lane finishes even later, forcing us to open another lane. This locally optimal dispatch rule is a greedy algorithm, powered by a min-heap — a tree-based priority queue that keeps the smallest completion timestamp at index 0 in O(1) time and updates in O(log n) time.
Why do simpler approaches fall short? Testing every pair of jobs for overlap takes O(n^2) time, and counting how many jobs intersect one long job isn't even accurate ([1, 10) overlaps [2, 3), [4, 5), and [6, 7), yet 2 servers run all four!). Meanwhile, assigning jobs in raw unsorted order can open extra servers needlessly if a late job claims a server before an earlier non-overlapping job. Sorting by start time and tracking completion timestamps in a min-heap finds the exact minimum in O(n log n) time.
Walk through [[2, 6], [4, 9], [6, 10]]:
- Sort by start timestamp (already ordered):
[2, 6),[4, 9),[6, 10). Start withfree_times = []. [2, 6): no servers exist yet, so open Server 1 finishing at6->free_times = [6].[4, 9): the earliest server frees up atfree_times[0] = 6 > 4(still busy!), so open Server 2 finishing at9->free_times = [6, 9].[6, 10): the earliest server frees up atfree_times[0] = 6 <= 6(just finished!), so pop6and push10to reuse Server 1 ->free_times = [9, 10].- Every job is scheduled, and
len(free_times) = 2servers were opened.
Complexity
Let n be the number of jobs in intervals.
- Time — O(n log n): Producing a sorted copy of the n jobs takes O(n log n) time. Next, we iterate through the n jobs once, running at most one
heappopand oneheappushper job; because the heap contains at most n timestamps, each heap operation runs in O(log n) time, giving O(n log n) overall. - Space — O(n):
sorted_tasksholds n interval references, andfree_timesstores one integer per allocated server (at most n integers when every job overlaps).
Edge cases
- Empty list (
[]): Returns0immediately without touching the heap. - Single job (
[[0, 5]]): Pushes one completion time and returns1. - Back-to-back touching jobs (
[[0, 4], [4, 7], [7, 11]]): Each job observesfree_times[0] == startand reuses the single server, returning1. - Duplicate windows (
[[3, 8], [3, 8], [3, 8]]): All begin at3whilefree_times[0] = 8 > 3, opening3distinct servers. - Simultaneous handoffs (
[[1, 3], [1, 3], [3, 5], [3, 5]]): Each[3, 5)job pops one3and pushes5, keeping the server count at2rather than4. - Early spike followed by quiet jobs (
[[1, 2], [1, 2], [5, 6]]): Popping at most one free server per incoming job (if, notwhile) leaves the second idle server infree_times, solen(free_times)stays2. - Zero-duration windows (
[t, t)): Standard half-open jobs satisfystart < end. If an interviewer permits degenerate[t, t)entries, clarify whether they are zero-time no-ops (if start == end: continue) or instantaneous tasks requiring a server slot.
Common mistakes
- Writing
<instead of<=(free_times[0] < start): Misclassifies abutting windows[0, 4)and[4, 7)as conflicting and opens 2 servers instead of 1. - Draining all idle servers with a
whileloop and returninglen(free_times): On[[1, 2], [1, 2], [5, 6]], awhileloop pops both idle servers before pushing6, shrinkinglen(free_times)to1even though 2 servers ran concurrently during[1, 2). - Skipping the initial sort: On
[[5, 8], [1, 3], [2, 6]], visiting jobs in raw input order places[5, 8)on Server 1, then sees8 > 1and8 > 2, opening 3 servers when 2 suffice ([1, 3)then[5, 8)on Server 1, and[2, 6)on Server 2). - Counting how many jobs overlap one specific job: A long job
[1, 10)can overlap three mutually disjoint short jobs[2, 3),[4, 5),[6, 7), which need 2 servers total, not 4. - Reversing event tie-breaking in a sweep line: If you convert windows into
(start, +1)and(end, -1)events, handling+1before-1at equal timestamps overcounts handoffs at timestampt.
Alternative approaches
- Sweep line over endpoint events: A sweep line algorithm slides a virtual time marker across all start and end timestamps in sorted order, maintaining a running count of active jobs. Emit
(start, +1)and(end, -1)for every window and sort all2ntuples; because Python orders(t, -1)before(t, +1)at identical timestampst, finishing jobs release their servers before starting jobs claim them, and the maximum running count gives the answer in O(n log n) time and O(n) space:
def minimum_servers_sweep(intervals: List[List[int]]) -> int:
events = []
for start, end in intervals:
events.append((start, 1))
events.append((end, -1))
events.sort()
active = 0
peak_servers = 0
for _, delta in events:
active += delta
if active > peak_servers:
peak_servers = active
return peak_servers
- Two sorted endpoint lists: Sort all
starttimestamps in one list and allendtimestamps in another, then march throughstartswhile advancing anend_idxpointer wheneverends[end_idx] <= start. Also O(n log n) time and O(n) space, though less convenient than a min-heap if asked to record concrete server IDs.
Follow-up questions
- How can you modify the scheduler to output a concrete server ID for every task? Store
(free_time, server_id)pairs in the min-heap, and tag each job with its original position(start, end, orig_idx)prior to sorting so you can populate the output list in input order. Wheneverfree_servers[0][0] <= start, pop and reuseserver_id; otherwise allocateserver_id = server_countand incrementserver_count, maintaining O(n log n) time and O(n) space:
def assign_servers(intervals: List[List[int]]) -> Tuple[int, List[int]]:
indexed_tasks = []
for orig_idx, (start, end) in enumerate(intervals):
indexed_tasks.append((start, end, orig_idx))
indexed_tasks.sort()
# free_servers: min-heap of (free_time, server_id)
free_servers: List[Tuple[int, int]] = []
assignment = [0] * len(intervals)
server_count = 0
for start, end, orig_idx in indexed_tasks:
if free_servers and free_servers[0][0] <= start:
_, server_id = heapq.heappop(free_servers)
else:
server_id = server_count
server_count += 1
assignment[orig_idx] = server_id
heapq.heappush(free_servers, (end, server_id))
return server_count, assignment
- If every timestamp is an integer minute within a single day (0 to 1440), can you beat O(n log n) time? Yes — allocate a difference array
diffof sizeT + 1 = 1441filled with zeros, add+1todiff[start]and-1todiff[end]for every job, and sweep a running prefix sum across0..1440to recover the exact active job count at every minute. Taking the maximum prefix sum runs in O(n + T) time and O(T) space, bypassing comparison sorting completely whenTis small. - How does the problem change if each server provides C CPU cores and task i consumes c_i cores instead of a whole server? Concurrent jobs can now co-exist on the same server whenever their summed core demands stay
<= C. Summing activec_idemands with a sweep line and computingceil(peak_cores / C)yields a valid lower bound, but computing the exact minimum server count becomes NP-hard (even if every job shares the exact same[start, end)window, it reduces directly to 1D bin packing!). Real cluster schedulers sort jobs and apply heuristics such as First-Fit or Best-Fit (packing each job onto the most-loaded server that still has at leastc_ifree cores atstart).
Follow-up questions
- How can you modify the scheduler to output a concrete server ID for every task?
- If every timestamp is an integer minute within a single day (0 to 1440), can you beat O(n log n) time?
- How does the problem change if each server provides C CPU cores and task i consumes c_i cores instead of a whole server?
Similar questions
- Go Concurrency Internals and Flight-Booking Storage Design
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One