Round-Robin Task Distribution with Dynamic Server Availability
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests stateful simulation with circular iteration, capacity tracking, and toggling availability flags.
You are implementing a task scheduler that distributes incoming jobs across multiple workers using a round-robin strategy. Each worker has a maximum number of tasks it can handle simultaneously, and workers can be temporarily taken offline for maintenance.
Write a function that processes a sequence of operations on the scheduler:
"assign_request": Allocate the next job to an available worker following round-robin order. Return the worker's index, or-1if no worker can accept the job."set_server_status": Change a worker's availability status (enabled or disabled). ReturnNone.
Round-robin behavior:
- Start searching from worker 0 initially.
- After assigning to worker
i, the next search begins at worker(i + 1) % n. - Search continues in circular order (wrapping around) until an available worker is found or all workers have been checked once.
- If no worker is found, return
-1and keep the search position unchanged.
Worker availability: A worker can accept a job if:
- It is currently enabled (not disabled for maintenance).
- Its current job count is strictly less than its capacity.
Important: Jobs are never removed once assigned. Disabling a worker preserves its job count; re-enabling it allows new assignments up to its original capacity limit.
Input:
capacities: List of integers wherecapacities[i]is the maximum job count for workeri.operations: List of operation names ("assign_request"or"set_server_status").arguments: List of argument lists. For"assign_request", the list is empty. For"set_server_status", it contains[worker_id, is_enabled]whereis_enabledis a boolean.
Output:
A list of results, one per operation. Each result is either an integer (worker index or -1) for "assign_request", or None for "set_server_status".
Constraints:
- 1 ≤ n ≤ 10⁴
- 1 ≤ capacities[i] ≤ 10⁶
- 1 ≤ number of operations ≤ 10⁴
- All workers start in the enabled state with 0 jobs assigned.
Examples
Example 1
Input: process_scheduler_operations([2, 1, 2], ['assign_request', 'assign_request', 'assign_request', 'set_server_status', 'assign_request'], [[], [], [], [1, False], []])
Output: [0, 1, 2, None, 0]
Hints
Hint 1
Maintain three pieces of state: current job count per worker, enabled status per worker, and the position where the next search will start.
Hint 2
Use modular arithmetic to wrap around: checking positions (start + 0) % n, (start + 1) % n, ..., (start + n-1) % n ensures you visit each worker exactly once.
Hint 3
Use a bounded loop (for offset in range(n)) instead of while True to guarantee termination when all workers are unavailable.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating a stateful round-robin scheduler. We track three pieces of information:
- Job counts (
job_counts[i]): How many jobs workericurrently holds. - Enabled flags (
is_enabled[i]): Whether workeriis currently available. - Search position (
search_start): The index where the next worker search begins.
For assign_request:
- Scan up to
nworkers starting fromsearch_start, wrapping around using modulo arithmetic. - The first worker that is both enabled and has remaining capacity gets the job.
- Increment that worker's job count, update
search_startto the next position, and return the worker's index. - If all
npositions are checked without success, return-1and leavesearch_startunchanged.
For set_server_status:
- Update the enabled flag for the specified worker and return
None. - Do not modify job counts or the search position.
Why This Works
Round-robin guarantee: By scanning positions (search_start + offset) % n for offset = 0, 1, ..., n-1, we visit every worker exactly once in circular order. The first match is by definition the "next available" worker.
Pointer advancement: After assigning to worker i, setting search_start = (i + 1) % n ensures the next search continues from the correct position, even if we skipped several workers.
Termination: Using for offset in range(n) bounds the scan. Without this limit, a while-loop could spin infinitely when all workers are unavailable.
State preservation: Failed assignments don't move the pointer (no assignment occurred, so the "next" position remains the same). Disabled workers retain their job counts, so re-enabling them resumes their participation with existing load.
Complexity
Time complexity:
- Each
assign_requestis O(n) in the worst case (scanning all workers). - Each
set_server_statusis O(1). - Overall: O(q × n) for q operations.
Space complexity: O(n) for state arrays plus O(q) for the results list.
Implementation
from typing import List, Optional
def process_scheduler_operations(capacities: List[int], operations: List[str], arguments: List[List]) -> List[Optional[int]]:
n = len(capacities)
job_counts = [0] * n
is_enabled = [True] * n
search_start = 0
results = []
for operation, args in zip(operations, arguments):
if operation == "assign_request":
assigned_worker = -1
for offset in range(n):
worker = (search_start + offset) % n
if is_enabled[worker] and job_counts[worker] < capacities[worker]:
job_counts[worker] += 1
assigned_worker = worker
search_start = (worker + 1) % n
break
results.append(assigned_worker)
elif operation == "set_server_status":
worker_id, enabled_flag = args
is_enabled[worker_id] = enabled_flag
results.append(None)
else:
raise ValueError("Unknown operation")
return results