#1882

Process Tasks Using Servers

Medium
ArrayHeap (Priority Queue)Priority QueueGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m log n)
Space
O(1)
O(n)
💡

Intuition

Time O(m log n)Space O(n)

The optimal solution uses two priority queues to efficiently manage free and busy servers. This allows us to quickly assign tasks to the most suitable server without scanning all servers repeatedly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two priority queues: one for free servers (sorted by weight and index) and one for busy servers (sorted by finish time).
  2. 2Step 2: For each task, check if any servers have finished processing and update the free servers queue.
  3. 3Step 3: If a free server is available, assign the task to it and update its busy status. If no servers are free, wait until the next server becomes available.
solution.py24 lines
1import heapq
2
3def assignTasks(servers, tasks):
4    n, m = len(servers), len(tasks)
5    ans = [-1] * m
6    free_servers = [(weight, i) for i, weight in enumerate(servers)]
7    heapq.heapify(free_servers)
8    busy_servers = []
9    time = 0
10
11    for j in range(m):
12        while busy_servers and busy_servers[0][0] <= time:
13            finish_time, server_index = heapq.heappop(busy_servers)
14            heapq.heappush(free_servers, (servers[server_index], server_index))
15
16        if len(free_servers) > 0:
17            weight, server_index = heapq.heappop(free_servers)
18            ans[j] = server_index
19            heapq.heappush(busy_servers, (time + tasks[j], server_index))
20        else:
21            time = busy_servers[0][0]
22            j -= 1  # Re-check the same task
23
24    return ans

Complexity note: This complexity arises from the use of priority queues, which allow for efficient insertion and extraction of servers, leading to logarithmic time complexity for each task.

  • 1Using priority queues allows for efficient management of server availability.
  • 2Tasks must be assigned in the order they arrive, which requires careful tracking of time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.