AlgoMaster Logo

Process Tasks Using Servers

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute-force Simulation

Intuition:

In a brute-force simulation approach, we can use an array to keep track of each server's availability. For each task, we iterate through the list of servers to find an available one. If none are available, we hold off the task until a server becomes free. This direct simulation is simple but not efficient because checking each server for availability takes linear time.

Steps:

  1. Use an array to represent available servers. Initialize it all to zero, representing that all servers are initially free.
  2. Iterate over each task:
    • Check all servers to find an available one. Mark the server as busy for the duration of the task.
    • If no server is free, wait until the earliest available server becomes free.
  3. Summarize the task allocation to servers.

Code:

2. Priority Queues for Efficient Assignment

Intuition:

The brute-force approach makes a key observation: it often checks all servers unnecessarily. We can optimize this using two priority queues:

  • One for free servers, sorted by their weight and index.
  • Another for busy servers, including when they become available again.

With these queues, tasks can be assigned more efficiently by popping from the priority queue.

Steps:

  1. Create two priority queues: one for available servers and one for busy servers.
  2. Iterate over tasks, and for each task, update the queue of busy servers to free any that have completed their tasks.
  3. Check the available servers queue. Assign the task to the server with the smallest weight and index.
  4. If no servers are free, update the next server that becomes available by waiting.

Code: