Problem · Design
Implement Malloc
Learn this problemProblem statement
Simulate a heap of heapSize bytes that starts as one free block at offset 0.
Process commands in order. Each command is one of:
ALLOC x: reserve a block ofxbytes after roundingxup to the next multiple of8. Choose a best-fit free block (the smallest free block that can hold the rounded size). Break ties by choosing the lowest start offset. Split any leftover tail back into the free list. Return that start offset, or-1if no free block is large enough.FREE offset: release the live allocation that starts atoffset. Adjacent free blocks must coalesce into one free block. AFREEof an unknown or already-freed offset is a no-op.
Return the list of ALLOC results in command order. FREE commands do not produce an output value.
Function
processMallocCommands(heapSize: int, commands: String[]) → int[]Examples
Example 1
heapSize = 32commands = ["ALLOC 8","ALLOC 16","FREE 0","ALLOC 8"]return = [0,8,0]ALLOC 8 takes offset 0. ALLOC 16 takes offset 8. FREE 0 reopens [0, 8). The next ALLOC 8 fits that hole and returns 0.
Example 2
heapSize = 48commands = ["ALLOC 24","ALLOC 8","FREE 0","ALLOC 8"]return = [0,24,32]After freeing offset 0, the free holes are [0, 24) and [32, 48). Best-fit for 8 bytes chooses the smaller hole at offset 32.
Constraints
8 <= heapSize <= 10^4.heapSizeis a multiple of8.1 <= commands.length <= 200.- Each command is
ALLOC xwith1 <= x <= heapSize, orFREE offsetwith an integer offset.