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 in category, mark that integer active for category, and return it.
  • "release" with [category, server_id]: Mark the currently active server_id in category as free again so later "allocate" calls for category can reassign it, and produce None.

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^5
  • operations[i] is either "allocate" or "release".
  • Every category is a non-empty string (compared case-sensitively).
  • Every "release" call targets a positive integer server_id that is currently active for that category.

Step-by-step walkthrough

  1. Understand the problem and the judge interface

    Each server category (such as "gpu", "cache", or "worker") manages its own independent sequence of positive server IDs 1, 2, 3, ...:

    • allocate(server_type) finds the smallest positive integer not currently in use by server_type, marks it in use, and returns it.
    • release(server_type, server_id) frees a currently in-use server_id so future allocate(server_type) calls can reuse it.
    • Different server categories never interfere with one another: "gpu" having ID 1 has no effect on "cache" also getting ID 1.

    The automated judge calls server_allocator(operations, arguments), where operations[i] is either "allocate" (with arguments[i] = [server_type]) or "release" (with arguments[i] = [server_type, server_id]), and expects a list of return values (int for "allocate", None for "release").

  2. 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 every allocate, tests 1, 2, 3, ... until it finds a number not in used[server_type].

    Why does that fail at 10^5 operations? Imagine 100,000 consecutive allocate("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 1 up to the highest ID handed out so far.

  3. 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, .... Let next_new be the smallest positive integer we have never allocated yet (starting at 1). That splits all free IDs into two clean regions:

    1. Brand-new IDs (next_new, next_new + 1, next_new + 2, ...): an infinite tail of untouched numbers, summarized by a single integer next_new.
    2. Recycled IDs (below next_new): numbers that were handed out earlier and later returned via release. We store these in a min-heap (Python's heapq, which keeps the smallest number at index 0 and supports inserting or popping the minimum in O(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 released min-heap before next_new? Because every ID in released was allocated in the past when next_new moved past it, and next_new never decreases. Therefore every recycled ID in released is strictly smaller than next_new!

    • If released is non-empty, its minimum (heapq.heappop) is guaranteed to be the smallest free ID overall.
    • If released is empty, every ID from 1 to next_new - 1 is currently in use, so next_new itself is the smallest free ID overall (and we increment next_new by 1).
  4. Implement `ServerAllocator`

    We keep two dictionaries keyed by server_type so each server type gets its own independent next_new counter and released min-heap:

    • On allocate(server_type), lazily initialize next_new[server_type] = 1 and released[server_type] = [] the first time we see server_type.
    • On release(server_type, server_id), push server_id onto released[server_type]. Because the problem guarantees release is only called on currently in-use IDs, server_type is already initialized and server_id cannot 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_type and server_id to avoid shadowing Python's built-in type and id functions.)

  5. Connect the `server_allocator` wrapper and trace Example 2

    server_allocator instantiates ServerAllocator, walks through (operations, arguments) with zip, appends the allocated ID for "allocate", and appends None for "release".

    Let's trace Example 2, where every operation targets "worker", paying attention to how release("worker", 3) followed by release("worker", 2) still returns 2 before 3:

    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        []           6
    

    Notice steps 5–7: even though 3 was released before 2, heapq.heappush places 2 at the root of the min-heap, so step 7 pops 2, step 8 pops 3, and step 9 resumes from next_new = 5.

  6. 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) per allocate or release (O(m log m) total across m calls). Looking up server_type in the dictionaries takes O(1) average time (hashing the string name once), and heapq.heappop or heapq.heappush walks at most one root-to-leaf path of height O(log r) in the binary heap (when the heap is empty, allocate simply increments next_new in O(1) time).
  • Space: O(T + R) (plus O(m) for the returned results list). Notice that currently in-use IDs take zero extra storage: any ID strictly below next_new[type] that is not sitting in released[type] is implicitly in use!

Edge cases

  • Empty operation list (operations = []): returns [] cleanly.
  • First allocation of a brand-new type: lazily initializes next_new = 1 and returns 1, unaffected by other types.
  • Releases arriving out of numerical order (release 3, then release 1): the min-heap surfaces 1 before 3, whereas a queue or stack would return the wrong order.
  • Releasing the highest allocated ID (allocate 1, 2, 3, then release 3): 3 enters released, and the next allocate pops 3 from the heap (since 3 < next_new = 4) before 4 is ever handed out.
  • Releasing all active IDs: subsequent allocations hand out 1, 2, 3, ... from the heap in order, then seamlessly resume at next_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 receive 2 instead of 1 after "gpu" took 1.
  • 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..N into each new type's heap: there is no fixed cap on IDs per type if someone allocates 10^5 servers, and pre-allocating 10^5 integers for each of 50,000 types would exhaust memory (5 * 10^9 entries).
  • Duplicate heap pushes when inputs are not trusted: here the prompt guarantees release is only called on currently in-use IDs, so duplicates cannot enter released. Without that guarantee, calling release("gpu", 1) twice would put two copies of 1 into the heap and hand ID 1 to two live servers! Defending against untrusted callers requires an in_use hash set (or a in_heap set) per type.

Alternative approaches

  • Balanced binary search tree / sorted set (such as SortedSet from third-party sortedcontainers, or std::set<int> in C++): achieves the same O(log r) allocate and release while also allowing O(log r) deletion of arbitrary elements and inspecting the maximum released ID.
  • Fixed-range bitset or segment tree: when the maximum ID N is small and fixed up front (like TCP port numbers 1..65535), a hierarchy of 64-bit bitmasks finds the lowest zero bit in O(1) hardware instructions with 1 bit of RAM per ID.

Follow-up questions

  • What is the worst-case runtime of each allocate and release call in your design? Heap sifting (heappush and heappop) compares elements along a single path of height floor(log2(r)), which is strictly O(log r) comparisons on every call, where r is 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 underlying list occasionally resizes the array in O(r) time (O(1) amortized), and Python dict lookup is O(L) average to hash a category string of length L (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 of released — only create self.released[category] when a category actually calls release, and del self.released[category] as soon as its heap becomes empty; (2) shrink the high-water mark — if server_id == self.next_new[category] - 1 on release, decrement self.next_new[category] instead of allocating a heap at all; and (3) evict idle categories — if self.next_new[category] == 1 (meaning zero servers of that category remain in use), delete category from self.next_new completely 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: reserved and in_use. If reserve(category) simply claims the smallest free ID temporarily, run the exact same selection logic as allocate(category) and record (category, id) in a reserved dictionary mapped to an expiration timestamp (time-to-live / TTL, so abandoned reservations do not leak IDs forever). Confirming a reservation moves id from reserved to in_use, while canceling (or lazily expiring via a global (expires_at, category, id) min-heap) removes it from reserved and pushes id back into self.released[category]. If reserve(category, specific_id) can instead lock an arbitrary caller-chosen specific_id before it is allocated, store unpopped reserved IDs in a per-category blocked set: allocate loops past any popped heap ID or next_new value present in blocked until it finds an unblocked ID.

Follow-up questions

Similar questions

More Oura interview questions

All 1 Oura questions →