Process Tasks Using Servers solution explained

Process Tasks Using Servers is a scheduling simulation: task j becomes ready at second j, and each ready task goes to the free server with the smallest weight, breaking ties by the smaller index. Keep two min-heaps, one of free servers keyed by (weight, index) and one of busy servers keyed by (time it frees up, weight, index). For each task, move the clock to at least j, release every server that has finished, and if none is free, jump the clock to the earliest finish time. That gives O((n + m) log n) for n servers and m tasks.

By Published 9 min read

The problem, restated

You have n servers, each with a weight, and m tasks, each with a running time in seconds. Task j joins a waiting line at second j. Whenever there are free servers and waiting tasks, the earliest waiting task goes to the free server with the lowest weight, and among equal weights the lowest index. A server that starts task j at second t becomes free again at second t + duration. If no server is free, tasks wait until one finishes. Return an array where entry j is the index of the server that ran task j.

Examples written for this page (outputs printed by the code below)
Server weightsTask durationsAssignment
[2, 1, 2][3, 1, 2, 4, 1][1, 0, 0, 1, 0]
[5][2, 2, 2][0, 0, 0]
[1, 1][1, 1, 1, 1][0, 0, 0, 0]
[3, 3, 1][10, 10, 10, 1][2, 0, 1, 2]
Examples written for this page (outputs printed by the code below). Scroll sideways on a small screen.

In the third example, each task finishes exactly when the next one arrives, and a server that finishes at second t is free at second t, so server 0 wins the tie on index every time. In the second, a single server makes every task wait for the one before it; the tasks start at seconds 0, 2 and 4.

What the interviewer is checking

This is a heap problem in a simulation wrapper. Interviewers want to see that you pick the right keys for each heap, that you handle the clock correctly when tasks pile up, and that you release every server that has finished, not just one. The most common failure is ticking the clock one second at a time, which works on small inputs and times out on long tasks. The second is releasing only servers that finish exactly now and forgetting ones that finished earlier while the clock jumped.

Questions to ask

  • When several tasks are waiting and several servers free up at once, who goes first? Waiting tasks keep their order, and each takes the best free server at that moment.
  • Does a server that finishes at second t count as free at second t? Yes.
  • Can weights repeat? Yes, which is why the index is part of the key.
  • How large can durations get? Large, which rules out stepping through every second.

A direct approach: scan every server

Keep each server's finish time in an array. For task j, set the clock to max(clock, j). Collect the servers whose finish time is at or before the clock; if there are none, move the clock to the smallest finish time and collect again. Pick the lowest (weight, index) among them. This is O(n) per task, O(n × m) in total, and it is a clean way to pin down the rules before optimizing.

def assign_tasks_scan(weights, durations):
    finish = [0] * len(weights)
    clock = 0
    result = []
    for j, length in enumerate(durations):
        clock = max(clock, j)
        if min(finish) > clock:
            clock = min(finish)
        best = None
        for s in range(len(weights)):
            if finish[s] <= clock and (best is None or weights[s] < weights[best]):
                best = s
        finish[best] = clock + length
        result.append(best)
    return result
Python: linear scan per task, O(n * m).

The loop keeps the first server it sees among equal weights because the comparison is strictly less than, which is the lowest-index tie-break for free.

Two heaps: the efficient version

The scan wastes time looking at every server. Replace the finish array with two heaps. The free heap answers "which free server is best" in O(log n). The busy heap answers "which server frees up next" in O(log n). For each task: set the clock to max(clock, j), pop every busy server whose finish time is at or before the clock into the free heap, and if the free heap is still empty, set the clock to the top finish time of the busy heap and release again. Then pop the best free server and push it onto the busy heap with its new finish time.

import heapq

def assign_tasks(weights, durations):
    free = [(w, i) for i, w in enumerate(weights)]
    heapq.heapify(free)
    busy = []
    clock = 0
    result = []
    for j, length in enumerate(durations):
        clock = max(clock, j)
        if not free:
            clock = max(clock, busy[0][0])
        while busy and busy[0][0] <= clock:
            done, w, i = heapq.heappop(busy)
            heapq.heappush(free, (w, i))
        w, i = heapq.heappop(free)
        heapq.heappush(busy, (clock + length, w, i))
        result.append(i)
    return result
Python: heapq for both heaps. O((n + m) log n).

Note the order: the clock jump happens before the release loop. If the free heap is empty, the clock moves to the earliest finish time, and then every server finishing at that same second is released together, so the best of them is chosen rather than whichever happened to sit on top of the busy heap.

class Heap {
  constructor(less) {
    this.items = [];
    this.less = less;
  }

  get size() {
    return this.items.length;
  }

  peek() {
    return this.items[0];
  }

  push(item) {
    const a = this.items;
    a.push(item);
    let c = a.length - 1;
    while (c > 0) {
      const p = (c - 1) >> 1;
      if (!this.less(a[c], a[p])) break;
      [a[c], a[p]] = [a[p], a[c]];
      c = p;
    }
  }

  pop() {
    const a = this.items;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let p = 0;
      for (;;) {
        const l = 2 * p + 1;
        const r = l + 1;
        let m = p;
        if (l < a.length && this.less(a[l], a[m])) m = l;
        if (r < a.length && this.less(a[r], a[m])) m = r;
        if (m === p) break;
        [a[m], a[p]] = [a[p], a[m]];
        p = m;
      }
    }
    return top;
  }
}

function assignTasks(weights, durations) {
  const byWeight = (x, y) => x[0] !== y[0] ? x[0] < y[0] : x[1] < y[1];
  const byFinish = (x, y) => x[2] !== y[2] ? x[2] < y[2] : byWeight(x, y);
  const free = new Heap(byWeight);
  const busy = new Heap(byFinish);
  weights.forEach((w, i) => free.push([w, i]));
  let clock = 0;
  const result = [];
  durations.forEach((length, j) => {
    clock = Math.max(clock, j);
    if (free.size === 0) clock = Math.max(clock, busy.peek()[2]);
    while (busy.size > 0 && busy.peek()[2] <= clock) {
      const [w, i] = busy.pop();
      free.push([w, i]);
    }
    const [w, i] = free.pop();
    busy.push([w, i, clock + length]);
    result.push(i);
  });
  return result;
}
JavaScript: a small binary heap with a comparator, then the same loop.

JavaScript has no built-in priority queue, so in an interview either write a compact heap like this one or say you would use a library and ask whether that is acceptable. The busy entries carry [weight, index, finish] so one comparator can fall back to the free-heap order on equal finish times, although for correctness any order among equal finish times works.

Trace on the first example

weights [2, 1, 2], durations [3, 1, 2, 4, 1]
TaskClockReleased before choosingChosen serverBusy until
0 (3 s)0none1 (weight 1)3
1 (1 s)1none0 (weight 2, lower index than server 2)2
2 (2 s)2server 00 (servers 0 and 2 free, same weight)4
3 (4 s)3server 11 (weight 1 is back)7
4 (1 s)4server 005
weights [2, 1, 2], durations [3, 1, 2, 4, 1]. Scroll sideways on a small screen.

No task waits in that run. The fourth example shows the jump: tasks 0, 1 and 2 take servers 2, 0 and 1 for ten seconds each, so at second 3 nothing is free. The clock jumps to 10, when server 2 finishes, and task 3 starts there on server 2, seven seconds after it arrived.

Complexity

n servers, m tasks, D = total of all durations
ApproachTimeExtra memory
Tick the clock one second at a timeO((m + D) × n) or worseO(n + m)
Scan every server per taskO(n × m)O(n)
Two heapsO((n + m) log n)O(n)
n servers, m tasks, D = total of all durations. Scroll sideways on a small screen.

Each task causes one pop and one push on each heap, plus releases; every release matches an earlier push, so releases add at most m pops over the whole run. Building the free heap takes O(n).

Edge cases

  • One server: every task runs on server 0, each starting when the previous one finishes or when it arrives, whichever is later.
  • More servers than tasks: no task ever waits.
  • All weights equal: the index decides, so the lowest free index wins every time.
  • Several servers finishing at the same second while tasks wait: all must be released before choosing.
  • Long durations with few servers: the clock runs far ahead of j, and later tasks start at the clock, not at their arrival second.

Common mistakes

  • Releasing only one finished server per task instead of every server whose finish time has passed.
  • Jumping the clock to j for every task, even when it is already later because tasks have been waiting.
  • Using the arrival second j instead of the clock as the start time, which makes waiting tasks finish too early.
  • Ordering the free heap by index only, or by weight only, instead of by the pair.
  • Stepping the clock forward one second at a time, which is correct but too slow when durations are long.

How to explain it out loud

Fictional example

Naming the two questions the code must answer fast
Candidate
At every assignment I need two answers quickly: which free server is best, and when does the next busy server free up. That is two heaps, one keyed by weight and index, one keyed by finish time.
Candidate
The clock is at least j. I release every busy server that has finished. If nothing is free, I jump the clock to the earliest finish, release again, and only then choose.
Interviewer
Why not just advance time second by second?
Candidate
Durations can be large, so that could take far more steps than there are tasks. With the jump, the work depends only on the number of tasks and servers: m log n plus building the heap.

Employee Free Time merges sorted schedules with a heap and reads the gaps. Merge k Sorted Lists practices the heap mechanics on their own. Reverse Pairs and Count of Range Sum are divide-and-conquer counting problems, useful for switching gears in a practice session.

Practicing with Natively

Simulation problems reward a clear statement of the rules before any code, and the clock jump is the rule people skip. Practice it out loud in a mock interview on Mac or Windows, with Natively transcribing so you can review whether you covered the waiting case. Once you have your own solution, Natively can read the problem from a screenshot and suggest an approach to check against it. See the AI interview assistant.

Questions people ask

How do you solve Process Tasks Using Servers?

Keep a min-heap of free servers by (weight, index) and a min-heap of busy servers by finish time. For task j, set the clock to at least j, release finished servers, jump to the earliest finish if none is free, then assign the best free server.

Why does the clock need to jump?

Tasks can pile up while every server is busy. Moving the clock straight to the next finish time avoids stepping through every second, which is too slow for long tasks.

What is the time complexity of Process Tasks Using Servers?

O((n + m) log n) for n servers and m tasks: building the free heap, then a constant number of heap operations per task plus releases that match earlier pushes.

How are ties between servers broken?

By weight first, then by the smaller index. Put both in the free heap's key, such as the tuple (weight, index).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP