Process Tasks Using Servers - Problem
Imagine you're managing a data center where multiple servers need to process incoming tasks efficiently. You have n servers with different processing capabilities (weights) and m tasks that arrive sequentially over time.
The Challenge: You need to assign each task to the most suitable available server following these rules:
- ๐ Task
jarrives at secondjand joins a queue - โ๏ธ Always assign tasks to the lightest available server (smallest weight)
- ๐ข If weights are equal, choose the server with the smallest index
- โณ A server processing a task becomes unavailable for
tasks[j]seconds - ๐ซ If no servers are free, tasks wait in queue until one becomes available
Goal: Return an array where ans[j] is the index of the server that processes task j.
Input: Two arrays - servers[i] (server weights) and tasks[j] (task durations)
Output: Array of server indices showing which server processes each task
Input & Output
example_1.py โ Basic Assignment
$
Input:
servers = [3,3,2], tasks = [1,2,3,2,1,2]
โบ
Output:
[2,2,0,2,1,2]
๐ก Note:
Tasks arrive at seconds 0,1,2,3,4,5. Server 2 (weight=2) is lightest and handles most tasks. When busy, tasks wait or use other servers based on availability and weight.
example_2.py โ All Servers Busy
$
Input:
servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
โบ
Output:
[1,4,1,4,1,3,2]
๐ก Note:
Server 1 (weight=1) is preferred but becomes busy. Tasks are assigned to next best available servers or wait for preferred servers to become free.
example_3.py โ Single Server
$
Input:
servers = [10], tasks = [1,1,1,1]
โบ
Output:
[0,0,0,0]
๐ก Note:
Only one server available, so all tasks must be assigned to server 0, with tasks queuing when the server is busy.
Constraints
- n == servers.length
- m == tasks.length
- 1 โค n, m โค 2 ร 105
- 1 โค servers[i], tasks[j] โค 2 ร 105
- All server weights and task durations are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Tasks Arrive
Tasks enter the system at regular intervals and join a processing queue
2
Find Best Server
System identifies the lightest available server (or waits for one to become free)
3
Assign & Process
Task is assigned to the selected server and begins processing
4
Update Status
Server status is updated and will become available again after task completion
Key Takeaway
๐ฏ Key Insight: Use two priority heaps to efficiently manage server availability and selection, achieving optimal O((m+n) ร log n) performance
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code