Round-Robin Load Balancer
Design a load balancer that spreads requests across a changing pool of servers in strict round-robin order.
Requirements
- The pool is an insertion-ordered list:
addServerappends to the end,removeServerdeletes in place and shifts the rest left. A duplicate add and a removal of an absent id are both no-ops. routeis strict round-robin. Keep an integercursor; on each call letidx = cursor mod n(wherenis the current pool size), returnservers[idx], then setcursor = idx + 1. This makes consecutive routes walk the list front-to-back and wrap around.- The cursor is an index evaluated at route time, so add/remove between routes simply changes what
cursor mod nlands on — a removal shifts later servers into earlier slots, exactly as list order dictates. routeon an empty pool returns-1and leaves the cursor unchanged.- No randomness, no weights, no real network — model the rotation as pure state.
API to implement
Implement the class LoadBalancer. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.
| Command | Returns | Behavior |
|---|---|---|
| addServer <id> | — | Add server id to the pool. Appended to the end of the insertion-ordered list; a duplicate id (already present) is ignored. |
| removeServer <id> | — | Remove server id from the pool if present; the servers after it shift one position left. Removing an absent id is a no-op. |
| route | int | Return the id of the next server in round-robin order and advance the cursor. Return -1 when the pool is empty (the cursor does not move). |
Input format
The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.
Output format
For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.
This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.
Sample cases
6
route
addServer 10
addServer 20
route
route
route-1
10
20
108
addServer 1
addServer 2
addServer 3
route
route
route
route
route1
2
3
1
2