Memory Allocator
Asked at OpenAI
Reported by the problem's creator, not verified
You manage a heap of size bytes with offsets 0 to size - 1. Implement a class Allocator that reserves and releases contiguous blocks of bytes. An allocated block never moves and nothing is ever copied: only offsets are tracked. When two free regions touch, they form a single free region.
Examples
Example 1
Input: init =
[10], operations =[["malloc",[3]],["malloc",[4]],["malloc",[5]],["free",[0]],["malloc",[5]],["free",[3]],["malloc",[5]],["free",[1]],["free",[0]],["free",[0]],["malloc",[10]],["malloc",[1]],["free",[0]],["malloc",[10]]]Output:
[0,3,-1,true,-1,true,0,false,true,false,0,-1,true,0]Explanation: After
malloc(3)andmalloc(4), only 3 bytes stay free, somalloc(5)fails. Freeing offset 0 leaves two 3-byte holes, still too small. Freeing offset 3 merges everything into one free region of 10, somalloc(5)returns 0. Offset 1 and the repeated 0 are not starts of allocated blocks, sofreereturns false.