Best-Fit Block Allocator with Coalescing and Log-Time Operations
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a best-fit extent allocator over a huge block range, where reserve and release must merge adjacent free runs and run in logarithmic time.
A storage service manages a volume of blocks blocks, numbered 0 to blocks - 1. At the start, every block is free. Files occupy extents, which are contiguous runs of blocks. You are given a batch of commands to run in order against one volume, and you must return what each command produces.
Commands
Command i has the name operations[i] and the integer list arguments[i].
"reserve" with arguments[i] = [n]
- Find a free run of at least
nblocks using the best-fit policy: choose the free run with the smallest length that is still>= n. If several free runs share that smallest length, choose the one with the lowest start address. - The extent is carved from the front of the chosen run. It occupies blocks
start .. start + n - 1. Any leftover blocks stay free as a shorter run beginning atstart + n. - The result is the start address of the new extent, or
-1if no free run is large enough. A failed reservation changes nothing. - If
n <= 0, raiseValueError.
"release" with arguments[i] = [start]
- Return the live extent that begins at
startto the free pool. The result isNone. - Coalescing: after the release, the freed run must merge with a free run that ends exactly at
startand with a free run that begins exactly where the extent ended. A later large request can then use the merged space. - If
startis not the start address of a currently live extent, raiseKeyError. This covers an address that was never handed out and an extent that was already released.
Any other command name raises ValueError.
Task
Implement the function so that it returns a list with one entry per command: the start address or -1 for "reserve", and None for "release". An exception raised while processing a command simply propagates out of the function.
Both reserve and release should run in O(log F) time, where F is the current number of free runs. Use only the standard library.
Constraints
0 <= blocks <= 10^12, so you cannot keep a per-block array.- Up to
10^6commands. reservearguments andreleasearguments are integers. Reservation sizes may exceedblocks, in which case the answer is-1.- A volume with
blocks = 0has no free runs. - Free runs are always kept fully merged: no two free runs are ever adjacent.
Examples
Example 1
Input: simulate_extent_allocator(100, ['reserve', 'reserve', 'reserve', 'reserve', 'release', 'reserve', 'release', 'release', 'reserve'], [[30], [20], [40], [20], [30], [15], [0], [30], [50]])
Output: [0, 30, 50, -1, None, 30, None, None, 0]
Example 2
Input: simulate_extent_allocator(100, ['reserve', 'reserve', 'reserve', 'reserve', 'release', 'release', 'reserve'], [[30], [10], [10], [50], [0], [40], [10]])
Output: [0, 30, 40, 50, None, None, 40]
Hints
Hint 1
Think of the free space as a set of runs, each described by (start, length). Which orderings do you need: one by length for choosing a run, and some way to find runs adjacent to a given address?
Hint 2
Best fit with the lowest-address tie-break is exactly a ceiling query on pairs (length, start): find the smallest pair that is >= (n, -infinity). Python has no built-in ordered set, so build a balanced or randomized BST, such as a treap.
Hint 3
Keep two dictionaries for free runs, one keyed by start address and one keyed by end address. Then on release you can check both neighbours in O(1). Route every change through one add helper and one remove helper so the structures cannot disagree.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the free space as a set of maximal runs. Never store individual blocks, since there can be up to 10^12 of them. Three lookups are needed, so we keep three structures, and they always describe the same set of free runs:
| Structure | Key -> value | Used for |
|---|---|---|
| Ordered set (treap) | (length, start) | Best fit: the smallest pair >= (n, -1) is the shortest sufficient run, with ties going to the lowest address |
head dict | start -> length | Is there a free run beginning exactly where a released extent ends? |
tail dict | end -> start | Is there a free run ending exactly where a released extent begins? |
live dict | start -> length | Validate release and recover the extent size |
All changes to the free runs go through two helpers, add_free and remove_free, which update the treap and both dictionaries together. That keeps them consistent.
reserve(n):
- Reject
n <= 0. - Run a ceiling query for
(n, -1)in the treap. If nothing is found, return-1. - Otherwise remove that run, and if it was longer than
n, add back the remainder starting atstart + n. Record the extent inliveand return its start.
release(start):
- Raise
KeyErrorunlessstartis inlive. - Compute the extent's end. If
headhas a run starting at that end, remove it and absorb its length. - If
tailhas a run ending atstart, remove it and extend the start backward. - Add the merged run.
Why it is correct
Free runs are always maximal. A release can only create adjacency with the run directly to its left or the run directly to its right, and the two dictionary lookups find exactly those. Because the treap is ordered by (length, start), the ceiling of (n, -1) is the pair with the smallest length >= n, and among equal lengths the smallest start. That is exactly best fit with a lowest-address tie-break. Carving from the front of the chosen run matches the specified placement.
Complexity
reserve: one ceiling query, one removal, and at most one insertion, so expectedO(log F).release:O(1)dictionary lookups plus at most two removals and one insertion, so expectedO(log F).- Space:
O(F + L), whereLis the number of live extents.
The treap uses random priorities, so its depth is O(log F) in expectation. Recursion depth in split and merge is therefore small, even for 10^6 commands.
Reference solution
import random
from typing import List, Optional
class _Node:
__slots__ = ("key", "prio", "left", "right")
def __init__(self, key, prio):
self.key = key
self.prio = prio
self.left = None
self.right = None
def _split(t, key):
"""Return (keys < key, keys >= key)."""
if t is None:
return None, None
if t.key < key:
t.right, r = _split(t.right, key)
return t, r
l, t.left = _split(t.left, key)
return l, t
def _merge(a, b):
"""All keys in a are smaller than all keys in b."""
if a is None:
return b
if b is None:
return a
if a.prio > b.prio:
a.right = _merge(a.right, b)
return a
b.left = _merge(a, b.left)
return b
def _insert(root, key, prio):
l, r = _split(root, key)
return _merge(_merge(l, _Node(key, prio)), r)
def _erase(root, key):
l, r = _split(root, key)
_, r2 = _split(r, (key[0], key[1] + 1))
return _merge(l, r2)
def _ceiling(root, key):
best = None
while root is not None:
if root.key >= key:
best = root.key
root = root.left
else:
root = root.right
return best
def simulate_extent_allocator(blocks: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
rng = random.Random(12345)
by_size = None # treap of (length, start)
head = {} # start -> length of each free run
tail = {} # end -> start of each free run
live = {} # start -> length of each reserved extent
def add_free(s, ln):
nonlocal by_size
by_size = _insert(by_size, (ln, s), rng.random())
head[s] = ln
tail[s + ln] = s
def remove_free(s):
nonlocal by_size
ln = head.pop(s)
del tail[s + ln]
by_size = _erase(by_size, (ln, s))
return ln
if blocks > 0:
add_free(0, blocks)
results = []
for op, args in zip(operations, arguments):
if op == "reserve":
n = args[0]
if n <= 0:
raise ValueError("reservation size must be positive")
hit = _ceiling(by_size, (n, -1))
if hit is None:
results.append(-1)
continue
ln, s = hit
remove_free(s)
if ln > n:
add_free(s + n, ln - n)
live[s] = n
results.append(s)
elif op == "release":
start = args[0]
if start not in live:
raise KeyError(start)
s = start
e = start + live.pop(start)
if e in head:
e += remove_free(e)
if s in tail:
s = tail[s]
remove_free(s)
add_free(s, e - s)
results.append(None)
else:
raise ValueError("unknown operation")
return results