Reusable Server ID Allocator
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Design an ID manager for cluster machines grouped by category names (such as "gpu", "cache", or "worker"). Each category maintains its own independent pool of positive integer IDs (1, 2, 3, ...), and categories never share IDs with one another.
Your allocator must support two operations:
"allocate"with[category]: Find the smallest positive integer (1, 2, 3, ...) that is not currently active incategory, mark that integer active forcategory, and return it."release"with[category, server_id]: Mark the currently activeserver_idincategoryas free again so later"allocate"calls forcategorycan reassign it, and produceNone.
Implement server_allocator(operations: List[str], arguments: List[List]) -> List[Optional[int]], which starts from an empty allocator, executes (operations[i], arguments[i]) in order, and returns the list of outputs (int for "allocate", None for "release").
Examples
Example 1
Input:
operations = ["allocate", "allocate", "allocate", "release", "allocate", "allocate"]
arguments = [["gpu"], ["gpu"], ["cache"], ["gpu", 1], ["gpu"], ["gpu"]]
Output:
[1, 2, 1, None, 1, 3]
Walk-through:
- "gpu" receives 1, then 2.
- "cache" has its own independent pool, so it receives 1.
- Releasing ("gpu", 1) returns 1 to "gpu"'s pool (None in output).
- The next "gpu" allocation reuses 1 before touching 3, and the final "gpu" allocation receives 3.
Example 2
Input:
operations = ["allocate", "allocate", "allocate", "allocate", "release", "release", "allocate", "allocate", "allocate"]
arguments = [["worker"], ["worker"], ["worker"], ["worker"], ["worker", 3], ["worker", 2], ["worker"], ["worker"], ["worker"]]
Output:
[1, 2, 3, 4, None, None, 2, 3, 5]
Walk-through: After "worker" allocates 1, 2, 3, 4, IDs 3 and 2 are released in that order. The next allocation picks 2 (the smallest free ID, even though 3 was released earlier), followed by 3, and then 5.
Example 3
Input:
operations = ["allocate", "allocate", "allocate", "release", "allocate", "release", "allocate"]
arguments = [["auth"], ["search"], ["auth"], ["auth", 2], ["search"], ["search", 1], ["auth"]]
Output:
[1, 1, 2, None, 2, None, 2]
Walk-through: "auth" allocates 1 and 2, releases 2, and later reclaims 2; meanwhile "search" allocates 1 and 2 and releases 1 without affecting "auth".
Constraints
0 <= len(operations) == len(arguments) <= 10^5operations[i]is either"allocate"or"release".- Every
categoryis a non-empty string (compared case-sensitively). - Every
"release"call targets a positive integerserver_idthat is currently active for thatcategory.
Step-by-step walkthrough
Understand the problem and the judge interface
Each server category (such as
"gpu","cache", or"worker") manages its own independent sequence of positive server IDs1, 2, 3, ...:allocate(server_type)finds the smallest positive integer not currently in use byserver_type, marks it in use, and returns it.release(server_type, server_id)frees a currently in-useserver_idso futureallocate(server_type)calls can reuse it.- Different server categories never interfere with one another:
"gpu"having ID1has no effect on"cache"also getting ID1.
The automated judge calls
server_allocator(operations, arguments), whereoperations[i]is either"allocate"(witharguments[i] = [server_type]) or"release"(witharguments[i] = [server_type, server_id]), and expects a list of return values (intfor"allocate",Nonefor"release").Why scanning from 1 on every allocation is too slow
The simplest possible implementation keeps a set
used[server_type]of active IDs and, on everyallocate, tests1, 2, 3, ...until it finds a number not inused[server_type].Why does that fail at
10^5operations? Imagine100,000consecutiveallocate("gpu")calls with zero releases:1st allocate("gpu"): checks 1 (1 step) 2nd allocate("gpu"): checks 1, 2 (2 steps) 3rd allocate("gpu"): checks 1, 2, 3 (3 steps) ... 100,000th call: checks 1, 2, ..., 100,000 (100,000 steps) Total work = 1 + 2 + ... + 100,000 ≈ 5,000,000,000 set lookups!Nearly all of that effort is wasted re-checking the solid block of busy IDs from
1up to the highest ID handed out so far.Key idea: split free IDs at a high-water mark `next_new`
For any single server category, think about the number line
1, 2, 3, .... Letnext_newbe the smallest positive integer we have never allocated yet (starting at1). That splits all free IDs into two clean regions:- Brand-new IDs (
next_new, next_new + 1, next_new + 2, ...): an infinite tail of untouched numbers, summarized by a single integernext_new. - Recycled IDs (below
next_new): numbers that were handed out earlier and later returned viarelease. We store these in a min-heap (Python'sheapq, which keeps the smallest number at index0and supports inserting or popping the minimum inO(log r)time).
Example for "worker" after allocating 1, 2, 3, 4 and releasing 3, then 2: 1 2 3 4 | 5 6 7 ... [used] [free] [free] [used] | [never allocated yet: >= next_new] ^ ^ | +---+---+ +-- next_new = 5 | released min-heap: [2, 3] --> smallest free ID overall is heap[0] = 2!Why do we check the
releasedmin-heap beforenext_new? Because every ID inreleasedwas allocated in the past whennext_newmoved past it, andnext_newnever decreases. Therefore every recycled ID inreleasedis strictly smaller thannext_new!- If
releasedis non-empty, its minimum (heapq.heappop) is guaranteed to be the smallest free ID overall. - If
releasedis empty, every ID from1tonext_new - 1is currently in use, sonext_newitself is the smallest free ID overall (and we incrementnext_newby1).
- Brand-new IDs (
Implement `ServerAllocator`
We keep two dictionaries keyed by
server_typeso each server type gets its own independentnext_newcounter andreleasedmin-heap:- On
allocate(server_type), lazily initializenext_new[server_type] = 1andreleased[server_type] = []the first time we seeserver_type. - On
release(server_type, server_id), pushserver_idontoreleased[server_type]. Because the problem guaranteesreleaseis only called on currently in-use IDs,server_typeis already initialized andserver_idcannot be pushed twice while already free.
class ServerAllocator: def __init__(self) -> None: # next_new: maps server_type -> smallest positive int never allocated yet (e.g. {"gpu": 3}) self.next_new: Dict[str, int] = {} # released: maps server_type -> min-heap of recycled free IDs < next_new (e.g. {"gpu": [1]}) self.released: Dict[str, List[int]] = {} def allocate(self, server_type: str) -> int: # Lazily initialize a server type on its first allocation. if server_type not in self.next_new: self.next_new[server_type] = 1 self.released[server_type] = [] # Every released ID was allocated earlier, so all IDs in `free_ids` are strictly # smaller than `next_new[server_type]`. Check the min-heap first! free_ids = self.released[server_type] if free_ids: return heapq.heappop(free_ids) # When no recycled IDs are waiting, hand out `next_new` and advance the high-water mark. new_id = self.next_new[server_type] self.next_new[server_type] = new_id + 1 return new_id def release(self, server_type: str, server_id: int) -> None: # By constraint, `server_id` was previously allocated and is currently in use, # so it is not already in `self.released[server_type]`. heapq.heappush(self.released[server_type], server_id)(We name the parameters
server_typeandserver_idto avoid shadowing Python's built-intypeandidfunctions.)- On
Connect the `server_allocator` wrapper and trace Example 2
server_allocatorinstantiatesServerAllocator, walks through(operations, arguments)withzip, appends the allocated ID for"allocate", and appendsNonefor"release".Let's trace Example 2, where every operation targets
"worker", paying attention to howrelease("worker", 3)followed byrelease("worker", 2)still returns2before3:Step Call Heap before next_new before Output Heap after next_new after ---- ---------------------- ----------- --------------- ------ ---------- -------------- 1 allocate("worker") [] 1 (initialized) 1 [] 2 2 allocate("worker") [] 2 2 [] 3 3 allocate("worker") [] 3 3 [] 4 4 allocate("worker") [] 4 4 [] 5 5 release("worker", 3) [] 5 None [3] 5 6 release("worker", 2) [3] 5 None [2, 3] 5 7 allocate("worker") [2, 3] 5 2 [3] 5 8 allocate("worker") [3] 5 3 [] 5 9 allocate("worker") [] 5 5 [] 6Notice steps 5–7: even though
3was released before2,heapq.heappushplaces2at the root of the min-heap, so step 7 pops2, step 8 pops3, and step 9 resumes fromnext_new = 5.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq class ServerAllocator: def __init__(self) -> None: # next_new: maps server_type -> smallest positive int never allocated yet (e.g. {"gpu": 3}) self.next_new: Dict[str, int] = {} # released: maps server_type -> min-heap of recycled free IDs < next_new (e.g. {"gpu": [1]}) self.released: Dict[str, List[int]] = {} def allocate(self, server_type: str) -> int: # Lazily initialize a server type on its first allocation. if server_type not in self.next_new: self.next_new[server_type] = 1 self.released[server_type] = [] # Every released ID was allocated earlier, so all IDs in `free_ids` are strictly # smaller than `next_new[server_type]`. Check the min-heap first! free_ids = self.released[server_type] if free_ids: return heapq.heappop(free_ids) # When no recycled IDs are waiting, hand out `next_new` and advance the high-water mark. new_id = self.next_new[server_type] self.next_new[server_type] = new_id + 1 return new_id def release(self, server_type: str, server_id: int) -> None: # By constraint, `server_id` was previously allocated and is currently in use, # so it is not already in `self.released[server_type]`. heapq.heappush(self.released[server_type], server_id) def server_allocator(operations: List[str], arguments: List[List]) -> List[Optional[int]]: # Replay the sequence of operations against a single ServerAllocator instance. allocator = ServerAllocator() results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "allocate": server_type = args[0] results.append(allocator.allocate(server_type)) elif op == "release": server_type, server_id = args[0], args[1] allocator.release(server_type, server_id) results.append(None) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine running coat-check counters with separate numbered tag rolls for "gpu", "cache", and "worker". For each server category, you keep a fresh roll of never-used tags starting at 1 (next_new) alongside a return bin (released) holding tags returned by departing servers. Whenever a new server requests an ID, if the return bin has any tags you hand out the lowest-numbered one; only when the return bin is empty do you tear off next_new and advance the roll to next_new + 1. Storing each category's state in a hash map (Python dict, giving O(1) average lookup by key) and organizing the return bin as a min-heap (a binary tree packed into a list where index 0 is always the minimum element, supporting insert and pop-min in logarithmic time) makes both allocate and release fast.
Why do simpler ideas fall short? Keeping a set of busy IDs and counting up 1, 2, 3, ... on every allocate re-scans every busy server from 1, turning 10^5 allocations of one category into roughly 5 * 10^9 checks. Conversely, pre-populating a heap with 1..100,000 for every new category wastes megabytes of memory when thousands of categories only ever allocate one or two IDs.
Here is a tiny trace on "worker" showing how next_new and the released min-heap work together:
1. allocate("worker") -> heap=[], next_new=1 -> returns 1 (next_new becomes 2)
2. allocate("worker") -> heap=[], next_new=2 -> returns 2 (next_new becomes 3)
3. allocate("worker") -> heap=[], next_new=3 -> returns 3 (next_new becomes 4)
4. release("worker", 3), then release("worker", 2) -> heap=[2, 3], next_new=4
5. allocate("worker") -> heap is non-empty, pop min -> returns 2 (heap=[3], next_new=4)
Complexity
Let m be the total number of operations, r be the number of released IDs currently waiting in a single type's min-heap (r <= m), T be the number of distinct server types seen, and R be the total number of released IDs currently stored across all heaps.
- Time:
O(log r)perallocateorrelease(O(m log m)total acrossmcalls). Looking upserver_typein the dictionaries takesO(1)average time (hashing the string name once), andheapq.heappoporheapq.heappushwalks at most one root-to-leaf path of heightO(log r)in the binary heap (when the heap is empty,allocatesimply incrementsnext_newinO(1)time). - Space:
O(T + R)(plusO(m)for the returnedresultslist). Notice that currently in-use IDs take zero extra storage: any ID strictly belownext_new[type]that is not sitting inreleased[type]is implicitly in use!
Edge cases
- Empty operation list (
operations = []): returns[]cleanly. - First allocation of a brand-new type: lazily initializes
next_new = 1and returns1, unaffected by other types. - Releases arriving out of numerical order (release
3, then release1): the min-heap surfaces1before3, whereas a queue or stack would return the wrong order. - Releasing the highest allocated ID (allocate
1, 2, 3, then release3):3entersreleased, and the nextallocatepops3from the heap (since3 < next_new = 4) before4is ever handed out. - Releasing all active IDs: subsequent allocations hand out
1, 2, 3, ...from the heap in order, then seamlessly resume atnext_new. - Case-sensitive type strings:
"gpu"and"Gpu"are distinct dictionary keys with independent pools.
Common mistakes
- Sharing a single counter or heap across all server types:
"cache"would receive2instead of1after"gpu"took1. - Using a FIFO queue (
deque) or LIFO stack (list.pop()) for released IDs: those return the earliest-released or most-recently-released ID rather than the smallest available positive integer. - Pre-filling
1..Ninto each new type's heap: there is no fixed cap on IDs per type if someone allocates10^5servers, and pre-allocating10^5integers for each of50,000types would exhaust memory (5 * 10^9entries). - Duplicate heap pushes when inputs are not trusted: here the prompt guarantees
releaseis only called on currently in-use IDs, so duplicates cannot enterreleased. Without that guarantee, callingrelease("gpu", 1)twice would put two copies of1into the heap and hand ID1to two live servers! Defending against untrusted callers requires anin_usehash set (or ain_heapset) per type.
Alternative approaches
- Balanced binary search tree / sorted set (such as
SortedSetfrom third-partysortedcontainers, orstd::set<int>in C++): achieves the sameO(log r)allocateandreleasewhile also allowingO(log r)deletion of arbitrary elements and inspecting the maximum released ID. - Fixed-range bitset or segment tree: when the maximum ID
Nis small and fixed up front (like TCP port numbers1..65535), a hierarchy of 64-bit bitmasks finds the lowest zero bit inO(1)hardware instructions with1bit of RAM per ID.
Follow-up questions
- What is the worst-case runtime of each allocate and release call in your design? Heap sifting (
heappushandheappop) compares elements along a single path of heightfloor(log2(r)), which is strictlyO(log r)comparisons on every call, whereris the number of released IDs in that category's heap. Two subtleties exist if an interviewer asks about true worst-case vs amortized time (average cost per operation over a worst-case sequence): appending to Python's underlyinglistoccasionally resizes the array inO(r)time (O(1)amortized), and Pythondictlookup isO(L)average to hash a category string of lengthL(degrading only under adversarial hash collisions). - How could you cut memory overhead when millions of distinct server categories exist and most allocate at most one ID? In our baseline, every seen category creates entries in two dicts plus an empty
[]list object. Three lightweight changes cut memory dramatically: (1) lazy initialization ofreleased— only createself.released[category]when a category actually callsrelease, anddel self.released[category]as soon as its heap becomes empty; (2) shrink the high-water mark — ifserver_id == self.next_new[category] - 1onrelease, decrementself.next_new[category]instead of allocating a heap at all; and (3) evict idle categories — ifself.next_new[category] == 1(meaning zero servers of that category remain in use), deletecategoryfromself.next_newcompletely so it consumes zero bytes! - How would you extend the allocator to support temporarily holding an ID before binding it to a live server? Split non-free IDs into two states:
reservedandin_use. Ifreserve(category)simply claims the smallest free ID temporarily, run the exact same selection logic asallocate(category)and record(category, id)in areserveddictionary mapped to an expiration timestamp (time-to-live / TTL, so abandoned reservations do not leak IDs forever). Confirming a reservation movesidfromreservedtoin_use, while canceling (or lazily expiring via a global(expires_at, category, id)min-heap) removes it fromreservedand pushesidback intoself.released[category]. Ifreserve(category, specific_id)can instead lock an arbitrary caller-chosenspecific_idbefore it is allocated, store unpopped reserved IDs in a per-categoryblockedset:allocateloops past any popped heap ID ornext_newvalue present inblockeduntil it finds an unblocked ID.
Follow-up questions
- What is the worst-case runtime of each allocate and release call in your design?
- How could you cut memory overhead when millions of distinct server categories exist and most allocate at most one ID?
- How would you extend the allocator to support temporarily holding an ID before binding it to a live server?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array