Custom Allocator with Coalescing - Problem
Design and implement a custom memory allocator that supports dynamic memory allocation and deallocation with block coalescing. Your allocator should manage a contiguous block of memory and provide two allocation strategies: first-fit and best-fit.
The allocator should maintain a free list of available memory blocks and automatically coalesce adjacent free blocks when memory is deallocated to prevent fragmentation.
Implement the following methods:
Allocator(size)- Initialize allocator with given memory sizeallocate(size, strategy)- Allocate memory using 'first-fit' or 'best-fit' strategy. Returns start address or -1 if allocation failsdeallocate(address, size)- Free memory block and coalesce adjacent free blocksgetFragmentation()- Return number of free blocks (measures fragmentation)
The input consists of operations to perform on the allocator. Each operation is represented as an array where the first element is the operation type.
Input & Output
Example 1 — Basic Allocation and Deallocation
$
Input:
memorySize = 1000, operations = [["allocate",100,"first-fit"],["allocate",200,"best-fit"],["deallocate",0,100],["getFragmentation"]]
›
Output:
[0,100,3]
💡 Note:
Allocate 100B at address 0, then 200B at address 100. After deallocating first block and coalescing, we have 3 free blocks total.
Example 2 — Best-fit vs First-fit Strategy
$
Input:
memorySize = 500, operations = [["allocate",100,"first-fit"],["allocate",50,"best-fit"],["getFragmentation"]]
›
Output:
[0,100,2]
💡 Note:
First-fit allocates 100B at start. Best-fit finds the smallest suitable block for 50B allocation.
Example 3 — Coalescing Adjacent Blocks
$
Input:
memorySize = 300, operations = [["allocate",100,"first-fit"],["allocate",100,"first-fit"],["deallocate",0,100],["deallocate",100,100],["getFragmentation"]]
›
Output:
[0,100,1]
💡 Note:
After deallocating adjacent blocks, they coalesce into a single 300B free block.
Constraints
- 1 ≤ memorySize ≤ 106
- 1 ≤ operations.length ≤ 1000
- 1 ≤ allocation size ≤ memorySize
- strategy ∈ {"first-fit", "best-fit"}
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code