Implement a first-fit memory allocator with an in-place free list and coalescing
Quick Overview
Implement a first-fit memory allocator over a fixed array that stores its free list metadata inside the array itself and merges neighboring free blocks on free. It tests in-place linked list updates, block splitting rules, coalescing, and careful pointer handling.
Implement a first-fit memory allocator with an in-place free list and coalescing
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: hard
Interview Round: Other
Design a memory allocator that manages a contiguous block of memory represented as an array of a given size. Each memory unit can store a 64-bit value. The allocator must support allocating contiguous blocks and freeing previously allocated blocks, all managed in place without using additional data structures for bookkeeping.
The allocator uses an in-place free list scheme. Free blocks store metadata directly in the memory array: the first unit of a free block stores the **negative** of the block's size (to distinguish free from allocated), and the second unit stores the index of the next free block (or `-1` if none). Allocated blocks store the **positive** block size in the first unit, and user data begins at the next unit.
When allocating `n` units, the allocator searches for a free block large enough to hold `n + 1` units (1 for metadata, `n` for data) using a first-fit strategy. It returns the index of the first usable data unit. If no suitable block exists, it returns `-1`. When a block is freed, it is reinserted into the free list and adjacent free blocks are coalesced to reduce fragmentation.
The allocator also supports reading and writing 64-bit values at allocated addresses.
The constructor `MemoryAllocator(size)` starts with the whole array as one free block. Implement these methods:
- `allocate(n: int) -> int`: Allocate a contiguous block of `n` memory units. Returns the starting index of the usable memory, or `-1` if allocation fails.
- `free(addr: int) -> None`: Free the previously allocated block whose usable memory starts at `addr`. Adjacent free blocks are coalesced.
- `read(addr: int) -> int`: Read the 64-bit value stored at the given memory address.
- `write(addr: int, value: int) -> None`: Write a 64-bit value to the given memory address.
Example 1:
```text
operations = ["MemoryAllocator", "allocate", "allocate", "write", "read", "free", "allocate", "write", "read"]
arguments = [[10], [3], [2], [1, 42], [1], [1], [4], [5, 99], [5]]
Output: [null, 1, 5, null, 42, null, -1, null, 99]
```
Create an allocator with 10 units. Allocate 3 units: it returns 1, and the block uses indices 0-3. Allocate 2 units: it returns 5, and the block uses indices 4-6, leaving a free block of 3 units at index 7. Write 42 to address 1, and reading address 1 returns 42. Free the block at address 1, which frees indices 0-3. Allocating 4 units needs 5 units, but the freed block at index 0 has 4 and the block at index 7 has 3, so it returns -1. Write 99 to address 5 (the second block is still allocated), and reading address 5 returns 99.
Example 2:
```text
operations = ["MemoryAllocator", "allocate", "allocate", "allocate", "free", "free", "allocate"]
arguments = [[20], [5], [3], [5], [1], [7], [10]]
Output: [null, 1, 7, 11, null, null, -1]
```
Create an allocator with 20 units. Allocate 5 (returns 1, block at indices 0-5), allocate 3 (returns 7, block at indices 6-9) and allocate 5 (returns 11, block at indices 10-15). A free block of 4 units remains at index 16. Free address 1, which frees a block of size 6. Free address 7, which frees a block of size 4 and coalesces it with the previous free block into one block of size 10. Allocating 10 needs 11 units: the coalesced block has 10 and the block at the end has 4, so it returns -1.
```hint Order of the free list
Pick an order for the free list that lets `free` find both physical neighbors of the block it releases during a single walk.
```
```hint Leftover units
When a split leaves only one spare unit, ask whether that unit can hold a free block's metadata, and where it should go so that `free` still gets every unit back.
```
```hint Merging on both sides
Trace a free whose block sits between two free blocks. Check which header survives and which next pointer it must end up with.
```
### Constraints & Assumptions
- `1 <= size <= 10⁴`
- `1 <= n <= size` for `allocate(n)`
- `free()` is only called with addresses previously returned by `allocate()`.
- All stored values are 64-bit integers.
- At most `10³` calls total to `allocate`, `free`, `read`, and `write`.
### Clarifying Questions to Ask
- Is the free list kept in address order, so first fit means the lowest-addressed free block that fits?
- If a split would leave a one-unit remainder, too small for a free block's two metadata units, should that unit go to the allocated block?
- May the head of the free list live in a variable outside the array, or must it be stored in the array too?
- Should `free` detect a double free or an address that `allocate` never returned, or can I assume valid calls?
- Should `read` and `write` check that the address lies inside an allocated block?
### What a Strong Answer Covers
- An exact layout for free and allocated block headers, and how the sign tells them apart.
- First-fit search with splitting, including what happens to a remainder too small to hold free-block metadata.
- Reinsertion on free that keeps the list in address order and merges with the free block before it, after it, or both.
- Correct free-list pointer updates when the head block is split, consumed or merged.
- The time and space cost of each operation, and the fragmentation trade-offs of first fit.
### Follow-up Questions
- How would boundary tags (a footer holding the size at the end of each block) let `free` coalesce in constant time?
- How would best fit or next fit change fragmentation and search time compared with first fit?
- How would you detect a double free or a write past the end of a block?
- How would you make the allocator safe to call from multiple threads?
Overview: Implement a first-fit memory allocator over a fixed array that stores its free list metadata inside the array itself and merges neighboring free blocks on free. It tests in-place linked list updates, block splitting rules, coalescing, and careful pointer handling.
Design a memory allocator that manages a contiguous block of memory represented as an array of a given size. Each memory unit can store a 64-bit value. The allocator must support allocating contiguous blocks and freeing previously allocated blocks, all managed in place without using additional data structures for bookkeeping.
The allocator uses an in-place free list scheme. Free blocks store metadata directly in the memory array: the first unit of a free block stores the negative of the block's size (to distinguish free from allocated), and the second unit stores the index of the next free block (or -1 if none). Allocated blocks store the positive block size in the first unit, and user data begins at the next unit.
When allocating n units, the allocator searches for a free block large enough to hold n + 1 units (1 for metadata, n for data) using a first-fit strategy. It returns the index of the first usable data unit. If no suitable block exists, it returns -1. When a block is freed, it is reinserted into the free list and adjacent free blocks are coalesced to reduce fragmentation.
The allocator also supports reading and writing 64-bit values at allocated addresses.
The constructor MemoryAllocator(size) starts with the whole array as one free block. Implement these methods:
allocate(n: int) -> int
: Allocate a contiguous block of
n
memory units. Returns the starting index of the usable memory, or
-1
if allocation fails.
free(addr: int) -> None
: Free the previously allocated block whose usable memory starts at
addr
. Adjacent free blocks are coalesced.
read(addr: int) -> int
: Read the 64-bit value stored at the given memory address.
write(addr: int, value: int) -> None
: Write a 64-bit value to the given memory address.
Create an allocator with 10 units. Allocate 3 units: it returns 1, and the block uses indices 0-3. Allocate 2 units: it returns 5, and the block uses indices 4-6, leaving a free block of 3 units at index 7. Write 42 to address 1, and reading address 1 returns 42. Free the block at address 1, which frees indices 0-3. Allocating 4 units needs 5 units, but the freed block at index 0 has 4 and the block at index 7 has 3, so it returns -1. Write 99 to address 5 (the second block is still allocated), and reading address 5 returns 99.
Create an allocator with 20 units. Allocate 5 (returns 1, block at indices 0-5), allocate 3 (returns 7, block at indices 6-9) and allocate 5 (returns 11, block at indices 10-15). A free block of 4 units remains at index 16. Free address 1, which frees a block of size 6. Free address 7, which frees a block of size 4 and coalesces it with the previous free block into one block of size 10. Allocating 10 needs 11 units: the coalesced block has 10 and the block at the end has 4, so it returns -1.
Constraints & Assumptions
1 <= size <= 10⁴
1 <= n <= size
for
allocate(n)
free()
is only called with addresses previously returned by
allocate()
.
All stored values are 64-bit integers.
At most
10³
calls total to
allocate
,
free
,
read
, and
write
.
Clarifying Questions to Ask Guidance
Is the free list kept in address order, so first fit means the lowest-addressed free block that fits?
If a split would leave a one-unit remainder, too small for a free block's two metadata units, should that unit go to the allocated block?
May the head of the free list live in a variable outside the array, or must it be stored in the array too?
Should
free
detect a double free or an address that
allocate
never returned, or can I assume valid calls?
Should
read
and
write
check that the address lies inside an allocated block?
What a Strong Answer Covers Guidance
An exact layout for free and allocated block headers, and how the sign tells them apart.
First-fit search with splitting, including what happens to a remainder too small to hold free-block metadata.
Reinsertion on free that keeps the list in address order and merges with the free block before it, after it, or both.
Correct free-list pointer updates when the head block is split, consumed or merged.
The time and space cost of each operation, and the fragmentation trade-offs of first fit.
Follow-up Questions Guidance
How would boundary tags (a footer holding the size at the end of each block) let
free
coalesce in constant time?
How would best fit or next fit change fragmentation and search time compared with first fit?
How would you detect a double free or a write past the end of a block?
How would you make the allocator safe to call from multiple threads?