Random Equipment Lending Pool with Constant-Time Operations
Data Structure DesignModel answerLast updated
Build an in-memory pool that lends out a uniformly random free item to a borrower, accepts returns, and allows retirement of idle items, with every operation in O(1) average time.
Fair-Rotation Equipment Pool
A security team keeps a fleet of wearable recording devices. At the beginning of a shift each staff member borrows one device, and at the end of the shift the device is returned. To spread usage evenly across the fleet, the system must hand out a uniformly random free device each time someone asks for one.
Implement a class DevicePool with the following methods:
add_device(device_id: str) -> bool: Adds a new device to the fleet. It begins in the free pool. ReturnsTrueif added,Falseif thatdevice_idis already known (whether free or lent out).retire_device(device_id: str) -> bool: Permanently deletes a device from the fleet. Only a free device can be deleted. ReturnsTrueon success, andFalseif the device is unknown or currently lent out.lend_random(staff_id: str) -> Optional[str]: Givesstaff_ida free device chosen uniformly at random and returns its ID. Each person may hold at most one device at once. ReturnsNoneif no device is free or if the person already holds one. A rejected request must not change any state.return_device(device_id: str) -> bool: Puts a lent device back into the free pool. ReturnsTrueon success, andFalseif the device is unknown or is not currently lent out.current_device(staff_id: str) -> Optional[str]: Returns the ID of the devicestaff_idcurrently holds, orNoneif they hold none.
Every operation must run in O(1) average time.
Constraints
1 <= len(device_id), len(staff_id) <= 64- IDs are alphanumeric (the hyphenated IDs in the example are for readability).
- At most
100,000calls in total across all methods. - Every free device must be equally likely to be chosen by
lend_random.
Example
pool = DevicePool()
pool.add_device("D1") # True
pool.add_device("D2") # True
pool.add_device("D3") # True
pool.add_device("D2") # False (already known)
d = pool.lend_random("alice") # one of D1, D2, D3 with probability 1/3 each; say "D2"
pool.current_device("alice") # "D2"
pool.lend_random("alice") # None (alice already holds a device)
pool.retire_device("D2") # False (currently lent out)
pool.return_device("D2") # True
pool.return_device("D2") # False (already free)
pool.retire_device("D2") # True
pool.return_device("D9") # False (never added)
What to cover
Describe your data structures, explain why they give O(1) time and uniform selection, handle the edge cases (empty pool, repeat borrowers, unknown or already-free devices, removing the last element of the internal array), and provide working code.
Hints
Hint 1
A hash set gives O(1) membership and deletion but cannot pick a random member in O(1). A plain array gives O(1) random indexing but deleting from the middle is O(n). Can you combine the two?
Hint 2
Keep free devices in a list, plus a dictionary from device ID to its position in that list. To delete an item at position i, overwrite it with the last list element, update that element's recorded position, then pop the tail.
Hint 3
Track lending with two dictionaries (device to holder, holder to device). Validate everything, including whether the person already holds a device and whether the pool is empty, before you modify any structure. Be careful when the element you delete is the last one in the list.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Each device is in exactly one state: free or lent out. The operations that must be O(1) are:
- Choose a uniformly random free device.
- Delete an arbitrary free device (
retire_device, and also the removal step insidelend_random). - Insert a device into the free pool (
add_device,return_device).
A set cannot do (1) in O(1), because sampling from it requires converting to a list, which is O(n). A list alone cannot do (2) in O(1), because removal from the middle shifts elements. The standard remedy is the "insert / delete / get-random" structure:
free: list[str]stores free device IDs, giving O(1) random access by index.pos: dict[str, int]maps each free device to its index infree.
Swap-and-pop deletion. To remove the element at index i, copy the last element into slot i, update that element's entry in pos, pop the tail, and delete the removed ID from pos. No shifting occurs, so it is O(1).
Lending is tracked with two dictionaries:
holder_of: dict[device, staff]device_of: dict[staff, device]
A device is known if and only if it is in pos (free) or in holder_of (lent). No separate "all devices" set is needed, which removes one more thing that could go out of sync.
Invariants
- Partition: every known device is in exactly one of
posorholder_of. - Index consistency: for each
dinpos,free[pos[d]] == d, andfreehas no duplicates. - Bijection:
holder_ofanddevice_ofare exact inverses; they are always updated together.
With these, each method's check is a single lookup:
retire_devicesucceeds only if the ID is inpos. That one test rejects both unknown and lent-out devices.return_devicesucceeds only if the ID is inholder_of. That rejects unknown and already-free devices.lend_randomfirst rejects a staff member already indevice_of, then an empty pool, and only then mutates anything.
Uniformity
random.randrange(len(free)) returns each index with probability 1/k, where k is the number of free devices. Because free holds exactly the free devices with no stale or duplicate entries, each free device is selected with probability 1/k.
Complexity
- Time: each method performs a constant number of dictionary operations, tail appends/pops, and at most one random draw, so O(1) average. "Average" reflects hashing and amortized list growth.
- Space: O(D + S), where D is the number of known devices and S is the number of staff currently holding one.
Code
import random
from typing import Optional
class DevicePool:
def __init__(self) -> None:
self._free: list[str] = []
self._pos: dict[str, int] = {}
self._holder_of: dict[str, str] = {}
self._device_of: dict[str, str] = {}
def _push_free(self, device_id: str) -> None:
self._pos[device_id] = len(self._free)
self._free.append(device_id)
def _pop_free_at(self, i: int) -> str:
removed = self._free[i]
last = self._free[-1]
self._free[i] = last
self._pos[last] = i # write first so i == last index is safe
self._free.pop()
del self._pos[removed] # delete after, so the self-swap case works
return removed
def add_device(self, device_id: str) -> bool:
if device_id in self._pos or device_id in self._holder_of:
return False
self._push_free(device_id)
return True
def retire_device(self, device_id: str) -> bool:
i = self._pos.get(device_id)
if i is None:
return False
self._pop_free_at(i)
return True
def lend_random(self, staff_id: str) -> Optional[str]:
if staff_id in self._device_of or not self._free:
return None
i = random.randrange(len(self._free))
device_id = self._pop_free_at(i)
self._holder_of[device_id] = staff_id
self._device_of[staff_id] = device_id
return device_id
def return_device(self, device_id: str) -> bool:
staff_id = self._holder_of.pop(device_id, None)
if staff_id is None:
return False
del self._device_of[staff_id]
self._push_free(device_id)
return True
def current_device(self, staff_id: str) -> Optional[str]:
return self._device_of.get(staff_id)
Edge cases
- Empty pool: return
Nonebefore callingrandrange, which raises on 0. - Repeat borrower: reject before touching the free list, so a refused request never consumes a device.
- Return of an unknown or already-free device: neither is in
holder_of, soFalse. - Retire a lent device: it is not in
pos, soFalse. - Re-adding after retirement: allowed, since the ID is fully purged.
- Deleting the last list element: the swap is with itself. Updating
pos[last]first and deletingpos[removed]second leaves the maps correct. - Shared ID namespace: staff and device IDs live in separate dictionaries, so a staff ID equal to a device ID causes no clash.
Common mistakes
- Using
random.choice(list(some_set)), which is O(n) per call. - Deleting with
list.removeorlist.pop(i), which is O(n). - Deleting the entry from
posbefore updating the moved element, which breaks when removing the tail. - Removing the device from the pool before verifying the staff member has no device, leaking a device on rejection.
- Keeping a separate "all devices" set that drifts out of sync with the others.
Trade-offs and follow-ups
- Thread safety: the compound updates need a lock (or a single-writer design), since lending touches several structures.
- Weighted selection (e.g., favor less-used devices) would need a Fenwick tree or similar, giving O(log n) rather than O(1).
- Persistence: back the maps with a database, using a transaction for lend and return so the structures stay consistent.