Memory Allocator

Asked at OpenAIPhone screen

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

  1. 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) and malloc(4), only 3 bytes stay free, so malloc(5) fails. Freeing offset 0 leaves two 3-byte holes, still too small. Freeing offset 3 merges everything into one free region of 10, so malloc(5) returns 0. Offset 1 and the repeated 0 are not starts of allocated blocks, so free returns false.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.