Best-Fit Block Manager with Splitting and Merging
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a best-fit memory manager on a fixed address range, handling splits, exact-start frees, invalid frees, and merging of neighboring free blocks using plain lists.
Best-Fit Block Manager with Splitting and Merging
You are managing a linear region of memory whose addresses run from 0 up to, but not including, capacity. At the start, the whole region is a single free block beginning at address 0.
You receive a list of requests and must process them in order. Each request is a pair (kind, value):
("alloc", size)asks for a block ofsizeunits.- Look at all free blocks whose length is at least
size, and pick the one with the smallest length. - If several qualify with the same smallest length, pick the one with the lowest starting address.
- Hand out the first
sizeunits of that block. Any leftover units at the end remain as a new, smaller free block. - The result of the request is the starting address of the handed-out block.
- If no free block is long enough, the result is
-1and nothing changes.
- Look at all free blocks whose length is at least
("free", pointer)gives back a previously handed-out block.- It succeeds only if some block that is currently handed out begins at exactly
pointer. In that case the block becomes free, it is merged with any free block that directly touches it on the left and/or on the right (so no two free blocks are ever adjacent), and the result is1. - Otherwise the result is
0and nothing changes. This covers an address that was never the start of a block, an address in the middle of a block, an address that is the start of a free block, and releasing the same block twice.
- It succeeds only if some block that is currently handed out begins at exactly
Return a list with one integer result per request, in the same order as the requests.
Function
Implement run_allocator(capacity, operations):
capacity: total number of address units.operations: list of(kind, value)pairs, wherekindis"alloc"or"free".- Returns a list of integers, one per request.
Constraints
1 <= capacity <= 10_0001 <= len(operations) <= 10_000- For
"alloc",sizeis an integer in[1, capacity]. - For
"free",pointeris an integer in[0, capacity - 1]. - Keep your state in plain Python lists and scalar variables. Do not use trees, heaps, hash maps/dicts/sets, ordered-map libraries, or
bisect. - If you keep a list ordered by size, write the binary search and insertion yourself.
- Block boundaries and merging must be derived from the state your code maintains, not from a precomputed answer.
Examples
Example 1
Input: run_allocator(8, [['alloc', 3], ['alloc', 2], ['free', 0], ['alloc', 4]])
Output: [0, 3, 1, -1]
Hints
Hint 1
Think about which questions you need to answer quickly: which free block is the best fit, who are a freed block's neighbors by address, and is a given pointer the start of a live block. Different orderings of the data suit different questions.
Hint 2
If you keep free blocks sorted by the pair (length, start), then the first entry with length >= size is exactly the best fit with the correct tie-break. A hand-written binary search finds it.
Hint 3
On free, a pointer that is not an exact start in the allocated list means result 0. Otherwise insert the block into the address-ordered free list and check only its immediate left and right neighbors for touching; remember to remove absorbed neighbors from every list that holds them.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Different requests need different questions answered, so keep three views of the state, each stored as a pair of parallel lists:
| View | Ordered by | Used for |
|---|---|---|
| Free blocks by address | start address | finding left/right neighbors when merging |
| Free blocks by size | (length, start) | finding the best fit |
| Allocated blocks | start address | checking whether a pointer is a live block start |
Alloc.
- Binary-search the size-ordered list for the first entry with length >= requested size. Because the list is sorted by
(length, start), that entry has the smallest sufficient length and, among equals, the lowest address. If there is no such entry, the answer is-1. - Remove that block from the size list and the address list.
- If it is longer than requested, the unused tail becomes a new free block, inserted into both free lists.
- Record the allocated block (kept sorted by start) and return its start.
Free.
- Binary-search the allocated list for an exact match on
pointer. No match means unknown pointer, interior pointer, a free block's start, or a double free, so return0. - Remove the block from the allocated list and insert it into the address-ordered free list.
- If the previous free block ends exactly at
pointer, merge with it (and drop it from the size list). - If the next free block starts exactly where the merged block ends, merge with it too.
- Insert the final merged block into the size list and return
1.
Why it is correct
- Free and allocated blocks always partition
[0, capacity): a split turns one free block into an allocated prefix plus a free suffix, and a free turns an allocated block into free space. - Both free lists always contain the same set of blocks, since every change updates both.
- No two free blocks are ever adjacent. A split suffix is bordered by the new allocated prefix on its left and by what bordered the original block on its right; a free merges with any touching neighbor. So a newly freed block can only touch its immediate predecessor and successor, and checking those two is enough.
- The
(length, start)ordering plus a lower-bound search on length produces exactly the required best-fit and tie-break choice. - Exact-match lookup on allocated starts rejects every invalid free.
Complexity
Let m be the number of operations and k the number of blocks tracked (at most capacity).
- Time: O(k) per operation, because list insertion, removal and the linear scans cost O(k) even though the binary searches are O(log k). Overall O(m * k).
- Space: O(k) for the lists plus O(m) for the output.
Reference solution
from typing import List, Tuple
def run_allocator(capacity: int, operations: List[Tuple[str, int]]) -> List[int]:
free_starts = [0]
free_sizes = [capacity]
size_starts = [0]
size_sizes = [capacity]
allocated_starts = []
allocated_sizes = []
result = []
def insert_size_block(start, size):
lo, hi = 0, len(size_sizes)
while lo < hi:
mid = (lo + hi) // 2
if (size_sizes[mid], size_starts[mid]) < (size, start):
lo = mid + 1
else:
hi = mid
size_starts.insert(lo, start)
size_sizes.insert(lo, size)
def remove_size_block(start, size):
for i in range(len(size_sizes)):
if size_starts[i] == start and size_sizes[i] == size:
size_starts.pop(i)
size_sizes.pop(i)
return
def insert_allocated(start, size):
lo, hi = 0, len(allocated_starts)
while lo < hi:
mid = (lo + hi) // 2
if allocated_starts[mid] < start:
lo = mid + 1
else:
hi = mid
allocated_starts.insert(lo, start)
allocated_sizes.insert(lo, size)
for operation, value in operations:
if operation == "alloc":
size = value
lo, hi = 0, len(size_sizes)
while lo < hi:
mid = (lo + hi) // 2
if size_sizes[mid] < size:
lo = mid + 1
else:
hi = mid
if lo == len(size_sizes):
result.append(-1)
continue
start = size_starts[lo]
block_size = size_sizes[lo]
size_starts.pop(lo)
size_sizes.pop(lo)
for i in range(len(free_starts)):
if free_starts[i] == start:
free_starts.pop(i)
free_sizes.pop(i)
break
if block_size > size:
suffix_start = start + size
suffix_size = block_size - size
pos = 0
while pos < len(free_starts) and free_starts[pos] < suffix_start:
pos += 1
free_starts.insert(pos, suffix_start)
free_sizes.insert(pos, suffix_size)
insert_size_block(suffix_start, suffix_size)
insert_allocated(start, size)
result.append(start)
else:
pointer = value
lo, hi = 0, len(allocated_starts)
while lo < hi:
mid = (lo + hi) // 2
if allocated_starts[mid] < pointer:
lo = mid + 1
else:
hi = mid
if lo == len(allocated_starts) or allocated_starts[lo] != pointer:
result.append(0)
continue
block_size = allocated_sizes[lo]
allocated_starts.pop(lo)
allocated_sizes.pop(lo)
pos = 0
while pos < len(free_starts) and free_starts[pos] < pointer:
pos += 1
free_starts.insert(pos, pointer)
free_sizes.insert(pos, block_size)
merged_start = pointer
merged_size = block_size
if pos > 0 and free_starts[pos - 1] + free_sizes[pos - 1] == pointer:
left_start = free_starts[pos - 1]
left_size = free_sizes[pos - 1]
remove_size_block(left_start, left_size)
merged_start = left_start
merged_size += left_size
free_starts.pop(pos)
free_sizes.pop(pos)
pos -= 1
if pos + 1 < len(free_starts) and merged_start + merged_size == free_starts[pos + 1]:
right_start = free_starts[pos + 1]
right_size = free_sizes[pos + 1]
remove_size_block(right_start, right_size)
merged_size += right_size
free_starts.pop(pos + 1)
free_sizes.pop(pos + 1)
free_starts[pos] = merged_start
free_sizes[pos] = merged_size
insert_size_block(merged_start, merged_size)
result.append(1)
return result