Aligned Free-List Memory Allocator
Learn this problemProblem statement
Implement an allocator for one fixed-size memory region. The region contains totalBytes bytes, begins at address 0, and is divided into blocks of alignment bytes.
You are given equal-length arrays operations and values. Process them in order:
allocaterequestsvalues[i]bytes. Round the request up to a whole number of alignment blocks, then reserve the first free contiguous range large enough to hold it. Return that range's starting address, or-1when no free range is large enough.freereleases the live allocation whose starting address isvalues[i]. Every free operation is guaranteed to reference a currently live allocation.
Return the addresses produced by allocate operations, in encounter order. Maintain free memory as an address-ordered linked list of maximal free ranges. Split a range when allocating and coalesce adjacent ranges when freeing.
Function
runAllocator(totalBytes: int, alignment: int, operations: String[], values: int[]) → int[]Examples
Example 1
totalBytes = 32alignment = 8operations = ["allocate","allocate","free","allocate"]values = [9,8,0,16]return = [0,16,0]The 9-byte request rounds up to 16 bytes and starts at 0. The 8-byte request starts at 16. Freeing address 0 makes the first 16 bytes available again, so the last request returns 0.
Example 2
totalBytes = 24alignment = 8operations = ["allocate","allocate","allocate","free","allocate"]values = [8,16,8,0,8]return = [0,8,-1,0]The first two allocations fill the region. The third request fails. After address 0 is freed, one block is available there and the final request succeeds.
Constraints
1 <= alignment <= 1024, andalignmentis a power of two.alignment <= totalBytes <= 1000000.totalBytesis divisible byalignment.0 <= operations.length <= 200000.operations.length == values.length.- Every operation is
allocateorfree. - For
allocate,1 <= values[i] <= totalBytes. - For
free,values[i]is the starting address of a live allocation.