Smallest Free Label per Category: Batch Simulation
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a sequence of allocate and release operations on independent categories, always handing out the smallest free positive integer, using a counter plus a min-heap per category.
A data center hands out numeric labels to machines. Machines are grouped by a category (a string), and each category keeps its own independent numbering. Within a category, a new machine always receives the smallest positive integer (1, 2, 3, ...) that no active machine of that category currently holds. When a machine is decommissioned, its label becomes free and may be handed out again.
You are given a list of operations and a parallel list of arguments. Process them in order and return one result per operation.
Operations
"allocate"with arguments[category]: give out the smallest positive integer not currently in use in that category, mark it as in use, and record that integer as the result."release"with arguments[category, label]: marklabelas free again in that category, and recordNoneas the result.
Categories never affect each other: the label 1 in "web" is unrelated to the label 1 in "db". A category that has never been seen before starts with every positive integer free.
Task
Implement a function that takes operations (a list of strings) and arguments (a list of lists, where arguments[i] belongs to operations[i]) and returns a list of the same length. The i-th element is the label produced by the i-th operation if it is an "allocate", or None if it is a "release".
Constraints
len(operations) == len(arguments), and the total number of operations is at most 10^5.- Each operation is either
"allocate"or"release". - A category is a non-empty string.
- A label is a positive integer.
- Every
"release"refers to a label that was previously handed out in that category and is currently in use (no double releases, no releasing unknown labels). - The returned list must have exactly one entry per operation, using
Nonefor releases.
Examples
Example 1
Input: label_allocator(['allocate', 'allocate', 'release', 'allocate', 'allocate'], [['web'], ['web'], ['web', 1], ['web'], ['db']])
Output: [1, 2, None, 1, 1]
Example 2
Input: label_allocator(['allocate', 'allocate', 'allocate', 'release', 'release', 'allocate', 'allocate', 'allocate'], [['api'], ['api'], ['api'], ['api', 2], ['api', 1], ['api'], ['api'], ['api']])
Output: [1, 2, 3, None, None, 1, 2, 4]
Example 3
Input: label_allocator(['allocate', 'allocate', 'release', 'allocate', 'release', 'allocate'], [['web'], ['db'], ['web', 1], ['web'], ['db', 1], ['db']])
Output: [1, 1, None, 1, None, 1]
Hints
Hint 1
Each category is an independent problem, so keep separate state for each one in a dictionary.
Hint 2
Within one category, every label below some counter has been handed out at least once. Free labels are either the 'holes' below that counter or the counter itself and everything above it.
Hint 3
Store the holes in a min-heap. On allocate, pop from the heap if it is non-empty, otherwise use the counter and increment it. On release, push the label onto the heap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each category as its own numbering space and keep state for it in a hash map. For one category the set of free labels always has a simple shape:
- A counter holding the smallest label that has never been handed out. Every label below it has been given out at some point.
- A min-heap of holes: labels below the counter that were released and are free again.
The smallest free label is the top of the heap if the heap is non-empty, and the counter otherwise.
- allocate: if the category's heap is non-empty, pop and return its minimum. Otherwise return the counter and increment it.
- release: push the label onto the category's heap and record
None.
Why it is correct
For a single category, the invariant is: the free labels are exactly the heap contents together with {counter, counter + 1, ...}, and every heap element is smaller than counter.
- Initially the heap is empty and the counter is 1, so all positive integers are free.
- On release, the label is guaranteed to be in use, so it was handed out earlier and is below the counter. Pushing it onto the heap keeps the invariant, with no duplicates.
- On allocate, if the heap is non-empty its minimum is smaller than the counter, so it is the smallest free label overall. If the heap is empty, the smallest free label is the counter. In both cases we remove exactly the label we return, preserving the invariant.
Categories share no state, so per-category correctness gives overall correctness. A category seen for the first time behaves as freshly initialized, which defaultdict provides.
Complexity
With n operations in total:
- Time: each operation costs O(log n) at worst for a heap push or pop, and O(1) on the counter path, so O(n log n) overall.
- Space: O(n) for the dictionary entries and heap contents.
Reference solution
import heapq
from collections import defaultdict
from typing import List, Optional
def label_allocator(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
# Per category: smallest label that has never been handed out.
counter = defaultdict(lambda: 1)
# Per category: min-heap of released labels waiting to be reused.
free_labels = defaultdict(list)
results: List[Optional[int]] = []
for op, args in zip(operations, arguments):
category = args[0]
if op == "allocate":
if free_labels[category]:
label = heapq.heappop(free_labels[category])
else:
label = counter[category]
counter[category] += 1
results.append(label)
else:
heapq.heappush(free_labels[category], args[1])
results.append(None)
return results