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_end and b_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 timestamp t ([t, b)).
  • If intervals contains zero jobs, return 0.

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

  1. Understand half-open intervals and overlap

    We receive n jobs, each written as [start, end) — a half-open interval covering start and 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 (returning 0 when intervals is empty).

    Because end is excluded, a job finishing at timestamp t and another starting at timestamp t never 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 server
    
  2. Why peak concurrency is the bottleneck

    Suppose at some instant t, k jobs are all running simultaneously. Every pair among those k jobs overlaps at t, so all k of 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 start timestamp and scans all n jobs to count how many satisfy s <= start < e. That finds the exact peak — since active concurrency only rises when a job begins — but scanning n jobs for each of the n start timestamps costs O(n^2) time, which times out at n = 100,000. We want O(n log n) time with a constructive server assignment.

  3. Key idea: sort by start time and track servers in a min-heap

    Simulate dispatching jobs in chronological start order:

    1. Sort intervals from earliest start to latest start.
    2. Maintain a min-heap free_times storing one entry per allocated server: the timestamp when its current job finishes. Because free_times is 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 pushing end.
    • Otherwise (free_times is empty or free_times[0] > start): even the earliest-finishing server remains busy past start, meaning every allocated server is currently occupied. Push end without 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 at s). Because we visit jobs in non-decreasing start order, all k - 1 existing servers are running jobs that started <= s. And because free_times[0] > s, all k - 1 of those jobs finish strictly after s. Including the new job, k jobs are simultaneously active at timestamp s — proving k servers are strictly required!

  4. Two subtle boundary rules: `<=` and popping at most once

    Before coding the loop, nail down two critical details:

    1. Use free_times[0] <= start, not <: Under half-open windows, a server whose previous job ended at 4 is immediately free at 4 to run [4, 7). Writing < would needlessly open a second server on Example 2.
    2. Use if, not while, when popping: Suppose two servers finished at 2 and the next job is [5, 6). Our single incoming job occupies only one idle server; the second server remains idle in free_times (with free time 2) ready for later jobs. Popping at most one entry preserves one heap entry per allocated server, so len(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)
    
  5. 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) = 4
    

    Notice the last step of Example 3: all four servers became free at 8, [8, 12) claimed one of them, and the other three stayed in free_times so the total server count remained 4.

  6. 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]]:

  1. Sort by start timestamp (already ordered): [2, 6), [4, 9), [6, 10). Start with free_times = [].
  2. [2, 6): no servers exist yet, so open Server 1 finishing at 6 -> free_times = [6].
  3. [4, 9): the earliest server frees up at free_times[0] = 6 > 4 (still busy!), so open Server 2 finishing at 9 -> free_times = [6, 9].
  4. [6, 10): the earliest server frees up at free_times[0] = 6 <= 6 (just finished!), so pop 6 and push 10 to reuse Server 1 -> free_times = [9, 10].
  5. Every job is scheduled, and len(free_times) = 2 servers 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 heappop and one heappush per 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_tasks holds n interval references, and free_times stores one integer per allocated server (at most n integers when every job overlaps).

Edge cases

  • Empty list ([]): Returns 0 immediately without touching the heap.
  • Single job ([[0, 5]]): Pushes one completion time and returns 1.
  • Back-to-back touching jobs ([[0, 4], [4, 7], [7, 11]]): Each job observes free_times[0] == start and reuses the single server, returning 1.
  • Duplicate windows ([[3, 8], [3, 8], [3, 8]]): All begin at 3 while free_times[0] = 8 > 3, opening 3 distinct servers.
  • Simultaneous handoffs ([[1, 3], [1, 3], [3, 5], [3, 5]]): Each [3, 5) job pops one 3 and pushes 5, keeping the server count at 2 rather than 4.
  • Early spike followed by quiet jobs ([[1, 2], [1, 2], [5, 6]]): Popping at most one free server per incoming job (if, not while) leaves the second idle server in free_times, so len(free_times) stays 2.
  • Zero-duration windows ([t, t)): Standard half-open jobs satisfy start < 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 while loop and returning len(free_times): On [[1, 2], [1, 2], [5, 6]], a while loop pops both idle servers before pushing 6, shrinking len(free_times) to 1 even 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 sees 8 > 1 and 8 > 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 +1 before -1 at equal timestamps overcounts handoffs at timestamp t.

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 all 2n tuples; because Python orders (t, -1) before (t, +1) at identical timestamps t, 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 start timestamps in one list and all end timestamps in another, then march through starts while advancing an end_idx pointer whenever ends[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. Whenever free_servers[0][0] <= start, pop and reuse server_id; otherwise allocate server_id = server_count and increment server_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 diff of size T + 1 = 1441 filled with zeros, add +1 to diff[start] and -1 to diff[end] for every job, and sweep a running prefix sum across 0..1440 to 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 when T is 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 active c_i demands with a sweep line and computing ceil(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 least c_i free cores at start).

Follow-up questions

Similar questions

More TripStack interview questions

All 2 TripStack questions →