Skip to content

Process Tasks Using Servers

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

You have servers with weights servers (server j has weight servers[j]) and a list of tasks, where task i takes tasks[i] seconds. Task i arrives at second i and joins a queue.

Whenever a server is free and the queue is not empty, the task at the front of the queue goes to the free server with the smallest weight, breaking ties by the smallest server index. If no server is free, tasks wait until one finishes. A server that starts task i at second t is free again at second t + tasks[i].

Return a list ans where ans[i] is the index of the server that runs task i.

servers = [3, 3, 2], tasks = [1, 2, 3, 2, 1, 2]  →  [2, 2, 0, 2, 1, 2]

Task 0 goes to server 2 (lightest) and finishes at second 1, just in time to take task 1. Task 2 arrives while server 2 is busy, so it goes to server 0.

Constraints

  • 1 <= servers.length, tasks.length <= 2 * 10^5
  • 1 <= servers[j], tasks[i] <= 2 * 10^5