Build a Heap Allocator with Fit Policies and Safe Handles
Data Structure DesignModel answerLast updated
Design a simulated memory manager over a fixed address range that supports two placement policies, splitting, merging of neighbors, and rejection of stale or forged release requests.
You are asked to build a simulated memory manager. It controls one contiguous range of addresses, 0 through total_size - 1. No real bytes are stored; the manager only tracks which address intervals are in use.
Behavior to implement
Placement policies
"FIRST_FIT": among free regions that are big enough (region_size >= requested), pick the one with the lowest start address."BEST_FIT": among free regions that are big enough, pick the smallest one. If several have the same size, pick the one with the lowest start address.
Splitting. If the chosen region is strictly larger than the request, the low-address part becomes the allocation and the leftover stays free directly after it. An exact fit must not create an empty region.
Merging. When an allocation is released, it must immediately combine with a free region directly before it and/or directly after it, so that two free regions are never adjacent.
Handle safety. allocate returns an opaque integer handle. free must return False, and leave all state untouched, when the handle was never issued, was already released, or refers to an address range that has since been given to a different request.
Interface
class Allocator:
def __init__(self, total_size: int, strategy: str = "FIRST_FIT"):
"""Manage total_size units of address space using the given policy."""
def allocate(self, size: int) -> int | None:
"""Return a handle for `size` contiguous units, or None if no free region is large enough."""
def free(self, handle: int) -> bool:
"""Release the allocation. Return True on success, False if the handle is invalid or stale."""
Constraints
1 <= total_size <= 10^91 <= size <= total_size- At most
10,000combined calls toallocateandfree strategyis"FIRST_FIT"or"BEST_FIT"
Example
a = Allocator(total_size=100, strategy="FIRST_FIT")
x = a.allocate(30) # occupies [0, 30)
y = a.allocate(20) # occupies [30, 50)
z = a.allocate(20) # occupies [50, 70)
a.free(y) # True; [30, 50) becomes free
a.free(y) # False; already released
a.free(99999) # False; never issued
w = a.allocate(15) # FIRST_FIT picks [30, 45); [45, 50) stays free
a.free(x) # frees [0, 30)
a.free(w) # frees [30, 45); merges with both sides into [0, 50)
What to cover in your answer
- The data structure you choose and why.
- How handles are generated and validated.
- The allocate and free algorithms, including tie-breaking and merging.
- Time and space complexity, and edge cases you would test.
- Possible optimizations if the number of operations were much larger.
Hints
Hint 1
Because total_size can reach 10^9, you cannot represent individual bytes. Store intervals (start, size, free-or-used) and keep them ordered by address so that they exactly tile the whole range.
Hint 2
If neighbors in your structure are also the physical neighbors in memory, merging on free is just a few pointer updates. Think about which linked structure gives you that in constant time.
Hint 3
Do not use the start address as the handle. A later allocation can land on the same address and make an old handle look valid. Consider an ever-increasing counter plus a map from handle to block that loses the entry on free.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Represent the address space as an address-ordered doubly linked list of blocks. Each block holds start, size, and a free flag. The blocks always tile [0, total_size) with no gaps or overlaps. Only intervals are stored, so memory use is independent of total_size.
Alongside the list, keep a dictionary handle -> block for live allocations, and a counter next_handle that only ever increases.
Allocate(size)
- Scan the list from the head to find a candidate free block with
block.size >= size.- First-fit: return the first such block encountered. Since the scan is in address order, this is the lowest address.
- Best-fit: remember the smallest qualifying block. Replace the current candidate only when a block is strictly smaller. Because the scan ascends in address, ties automatically keep the lowest address. Stop early on an exact fit.
- If nothing qualifies, return
None. - If the block is larger than the request, split: create a new free block at
start + sizewith the leftover size, link it right after the block, and shrink the block tosize. If it is an exact fit, do nothing, so no zero-size block appears. - Mark the block used, assign
handle = next_handle, increment the counter, storehandles[handle] = block, and return the handle.
Free(handle)
- If
handleis not in the dictionary, returnFalseimmediately, with no mutation. - Remove the entry from the dictionary and mark the block free.
- If
block.nextis free, absorb it: add its size and unlink it. - If
block.previs free, let the previous block absorb this one. - Return
True.
Since the list is address-ordered, list neighbors are physical neighbors, so merging is O(1).
Why handles must be fresh IDs
Using the start address as the handle is the classic mistake. Suppose y = 30 is freed and a new request then lands at address 30. A second free(30) would now succeed and release someone else's memory. With a monotonically increasing counter and removal from the dictionary on free:
- never-issued handles are absent from the map,
- already-freed handles were removed,
- handles whose range was reused are still absent, because the new allocation received a different ID.
All three cases are rejected with False and zero state change. Integer IDs in Python do not overflow, so reuse is not a concern. In a language with fixed-width integers, you could add a generation counter or a 64-bit ID.
Correctness invariants
- Tiling: for every block,
block.start + block.size == block.next.start, the first starts at 0, and the last ends attotal_size. Splitting swaps one block for two adjacent pieces of equal total size; merging does the reverse. - Maximal coalescing: no two adjacent blocks are both free. Initially there is one block. Allocation turns free into used, and a split remainder is adjacent to the used block on one side and to what was already the next block on the other (which was not free, by the invariant). Free merges with both neighbors, restoring the property.
Complexity
Let B be the number of blocks. With coalescing, B <= 2 * (live allocations) + 1.
| Operation | Time | Notes |
|---|---|---|
allocate | O(B) | Linear scan; best-fit scans everything unless an exact fit appears |
free | O(1) | Dict lookup plus constant-time merges |
| Space | O(B) | Blocks plus handles; independent of total_size |
With 10,000 operations, B is at most about 10^4, so the worst case is on the order of 10^8 simple steps in total and typically far less. That is acceptable.
Code
class _Block:
__slots__ = ("start", "size", "free", "prev", "next")
def __init__(self, start, size, free=True):
self.start, self.size, self.free = start, size, free
self.prev = self.next = None
class Allocator:
def __init__(self, total_size: int, strategy: str = "FIRST_FIT"):
if total_size <= 0:
raise ValueError("total_size must be positive")
if strategy not in ("FIRST_FIT", "BEST_FIT"):
raise ValueError("unknown strategy")
self.total_size = total_size
self.strategy = strategy
self._head = _Block(0, total_size)
self._handles = {}
self._next = 1
def _find(self, size):
best, node = None, self._head
while node:
if node.free and node.size >= size:
if self.strategy == "FIRST_FIT":
return node
if best is None or node.size < best.size:
best = node
if node.size == size:
break
node = node.next
return best
def allocate(self, size):
if size <= 0 or size > self.total_size:
return None
blk = self._find(size)
if blk is None:
return None
if blk.size > size:
rest = _Block(blk.start + size, blk.size - size)
rest.prev, rest.next = blk, blk.next
if blk.next:
blk.next.prev = rest
blk.next = rest
blk.size = size
blk.free = False
h = self._next
self._next += 1
self._handles[h] = blk
return h
def free(self, handle):
blk = self._handles.pop(handle, None)
if blk is None:
return False
blk.free = True
nxt = blk.next
if nxt and nxt.free: # absorb successor
blk.size += nxt.size
blk.next = nxt.next
if nxt.next:
nxt.next.prev = blk
prv = blk.prev
if prv and prv.free: # be absorbed by predecessor
prv.size += blk.size
prv.next = blk.next
if blk.next:
blk.next.prev = prv
return True
Edge cases to test
- Exact fit: no zero-size block is created.
- Allocating the whole space, then requesting again: returns
None. - Fragmentation: enough total free bytes but no single region large enough returns
None. - Free with both neighbors free: three-way merge leaves one block.
- Freeing the first or last block (a
Noneneighbor). - Best-fit tie between equal-size holes: lowest address wins.
- Double free, forged handle, and handle whose range was reused: all return
False. - Invalid constructor arguments raise
ValueError.
Common mistakes
- Using the address as the handle, which breaks stale detection.
- Merging only with the next neighbor and forgetting the previous one.
- Using
<=in the best-fit comparison, which breaks the lowest-address tie rule. - Mutating state before validating the handle.
- Allocating a byte array of size
total_size.
Follow-ups
To make allocation faster than O(B), keep free blocks in a structure keyed by size, such as a balanced tree or segregated size-class lists, for best-fit. For first-fit, use a segment tree over blocks storing the maximum free size per subtree. Both keep the address-ordered list for O(1) merging, at the cost of extra bookkeeping on every split and merge.