KatInterview

Round-Robin Task Distribution with Dynamic Server Availability

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designsimulationcircular-iterationstate-management

Last 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 -1 if no worker can accept the job.
  • "set_server_status": Change a worker's availability status (enabled or disabled). Return None.

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 -1 and keep the search position unchanged.

Worker availability: A worker can accept a job if:

  1. It is currently enabled (not disabled for maintenance).
  2. 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 where capacities[i] is the maximum job count for worker i.
  • 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] where is_enabled is 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.