OpenAI questions

Memory Allocator

OpenAIPhone screenMedium

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.

Part 1: First-fit with merging

Allocator(size) starts with all size bytes free.

  • malloc(k) reserves k contiguous free bytes at the start of the lowest-address free region that has at least k bytes, and returns that offset. If no free region is long enough, it returns -1.
  • free(ptr) releases the block that starts at offset ptr and returns true. If ptr is not the start of a currently allocated block — inside a block, already freed, out of range, or never allocated — it returns false and changes nothing.
  1. Example 1
    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]

    Why: 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.

Constraints

  • 1 <= size <= 10^6
  • 1 <= k <= 10^6
  • 1 <= len(operations) <= 10^3
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Memory Allocator: OpenAI interview question | LoopCoach