Contiguous Block Allocator with Tag-Based Memory Management
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests segment tree design for efficiently finding and tracking contiguous free blocks in a memory-like array with logarithmic-time allocation and release operations.
You need to implement a memory allocator that manages n cells in a linear array (indexed 0 through n-1). Initially, all cells are free.
Your allocator must support two operations through a sequence of commands:
-
allocate(length, tag): Find the smallest index
iwhere cells[i, i+length-1]are all free. Mark those cells with the given identifiertagand returni. If no contiguous block of that size exists, return-1. -
release(tag): Free all cells currently marked with the identifier
tagand return the count of cells freed. If the tag doesn't exist or has no allocated cells, return0.
Implement a function that processes a sequence of these operations and returns a list of results (one integer per operation).
Important behaviors:
- Multiple
allocatecalls with the same tag accumulate cells under that tag - A single
releasefrees all cells owned by that tag allocatealways chooses the lowest valid starting index- Invalid lengths (
length <= 0orlength > n) immediately return-1 - Fragmentation may prevent allocation even when total free cells exceed the requested length
Constraints:
0 <= n <= 100,0001 <= number of operations <= 10,0001 <= length <= nfor valid allocations1 <= tag <= 10^9- All operations are either
"allocate"or"release"
Examples
Example 1
Input: block_allocator(10, ['allocate', 'allocate', 'release', 'allocate'], [[3, 1], [2, 2], [1], [4, 3]])
Output: [0, 3, 3, 5]
Example 2
Input: block_allocator(5, ['allocate', 'allocate', 'release', 'release'], [[2, 7], [2, 7], [7], [99]])
Output: [0, 2, 4, 0]
Example 3
Input: block_allocator(4, ['allocate', 'allocate', 'allocate', 'release'], [[0, 1], [5, 2], [2, 3], [3]])
Output: [-1, -1, 0, 2]
Hints
Hint 1
Use a segment tree where each node tracks the longest free prefix, suffix, and interior run within its range to enable O(log n) searches.
Hint 2
When searching for a block, check the left subtree first, then runs crossing the midpoint, then the right subtree to guarantee the lowest starting index.
Hint 3
Store a map from each tag to the set of cell indices it owns to handle release operations and allow tags to accumulate multiple allocations.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A naive scan to find the first contiguous free block costs O(n) per allocation. To achieve O(log n) performance, we use a segment tree where each node maintains three statistics about its range:
- prefix: longest run of free cells starting at the left boundary
- suffix: longest run of free cells ending at the right boundary
- best: longest free run anywhere in the range
These values can be computed from child nodes in constant time. For a parent node covering a range split at the midpoint:
prefix = left.prefix + (right.prefix if left fully free else 0)
suffix = right.suffix + (left.suffix if right fully free else 0)
best = max(left.best, right.best, left.suffix + right.prefix)
The tree is padded to the next power of two. Padding leaves are treated as occupied, preventing any free run from extending beyond cell n-1.
Finding the lowest starting index: Starting at the root, we check three possibilities in priority order:
- If the left child's
best >= length, the answer must be in the left half (recurse left) - Else if
left.suffix + right.prefix >= length, a run spans the midpoint starting atmid - left.suffix - Else recurse right
This left-to-right priority guarantees we find the lowest valid index. If root.best < length, we immediately return -1.
Tag management: We maintain a hash map from each tag to the set of cell indices it currently owns. When allocate succeeds, we add the new cells to that tag's set (allowing accumulation across multiple calls). When release is called, we pop the tag's entire set, free each cell, and return the count.
Why it works
The merge rules are exhaustive: any maximal free run in a parent's range either lies entirely in one child or crosses the midpoint. Induction guarantees correctness at every level.
The search strategy ensures the lowest index because:
- Any run entirely in the left half has a lower start than any crossing or right-half run
- If no such run exists, the earliest crossing run begins at
mid - left.suffix - Only when both fail can the answer lie in the right half
Fragmentation is handled naturally—the tree always reflects the current free/occupied state after any sequence of operations.
Complexity
-
Time per operation:
allocate: O(log n) for the search + O(k log n) to mark k cellsrelease: O(k log n) to free k cells- Overall amortized cost is O(log n) per operation since each cell can only be allocated and freed once per cycle
-
Space: O(n) for the segment tree and tag-to-cells map
Implementation
from typing import List
def block_allocator(n: int, operations: List[str], arguments: List[List[int]]) -> List[int]:
if n < 0:
raise ValueError("n must be non-negative")
# Round up to next power of two for segment tree
size = 1
while size < max(1, n):
size <<= 1
# Each node stores: longest free prefix, suffix, and maximum run
prefix = [0] * (2 * size)
suffix = [0] * (2 * size)
best = [0] * (2 * size)
def pull(p: int) -> None:
"""Recompute aggregates for node p from its children."""
left, right = 2 * p, 2 * p + 1
left_len = (size >> (p.bit_length() - 1)) // 2
prefix[p] = prefix[left] + (prefix[right] if prefix[left] == left_len else 0)
suffix[p] = suffix[right] + (suffix[left] if suffix[right] == left_len else 0)
best[p] = max(best[left], best[right], suffix[left] + prefix[right])
# Initialize leaves: real cells free, padding occupied
for i in range(size, size + n):
prefix[i] = suffix[i] = best[i] = 1
# Build tree bottom-up
for i in range(size - 1, 0, -1):
pull(i)
def update(pos: int, free: bool) -> None:
"""Mark cell at pos as free or occupied."""
p = size + pos
v = 1 if free else 0
prefix[p] = suffix[p] = best[p] = v
p //= 2
while p:
pull(p)
p //= 2
def find_first(length: int) -> int:
"""Return lowest index where length consecutive free cells start, or -1."""
if n == 0 or best[1] < length:
return -1
node, lo, hi = 1, 0, size
while hi - lo > 1:
mid = (lo + hi) // 2
left, right = 2 * node, 2 * node + 1
if best[left] >= length:
node, hi = left, mid
elif suffix[left] + prefix[right] >= length:
return mid - suffix[left]
else:
node, lo = right, mid
return lo
allocated = {} # tag -> set of owned cell indices
results = []
for op, args in zip(operations, arguments):
if op == "allocate":
length, tag = args
if length <= 0 or length > n:
results.append(-1)
continue
start = find_first(length)
if start < 0 or start + length > n:
results.append(-1)
continue
cells = allocated.setdefault(tag, set())
for pos in range(start, start + length):
cells.add(pos)
update(pos, False)
results.append(start)
elif op == "release":
tag = args[0]
cells = allocated.pop(tag, set())
results.append(len(cells))
for pos in cells:
update(pos, True)
else:
raise ValueError("unknown operation")
return results