1/34
Part 1 of 7 · alloc and freeLearn

Memory allocator

Design Memory Allocator, LeetCode 2502, is on OpenAI's LeetCode company tag lists, the all-time, three-month and six-month ones (3 sources). Three OpenAI candidates report it under the name malloc, one as the only question, with some tests provided (3 reports). It starts like this:

Build Allocator(size) for an arena of size units, at addresses 0 to size - 1. A block is a run of units in a row, known by its start address. A size below 1 raises ValueError.

  • alloc(n) hands out a block of n units and returns its start: the lowest address where n free units in a row begin. When no such run exists, it returns None and changes nothing, even if enough units are free in total. An n below 1 raises ValueError.
  • free(addr) frees the live block that starts at addr and returns the number of units it held. Any other address raises ValueError and changes nothing: one inside a block, a free one, one outside the arena, and the start of a block that was freed already.
Call on Allocator(10)Returns
alloc(3)0
alloc(4)3
alloc(2)7
alloc(2)None, because only unit 9 is free
free(3)4, the size of the block at 3
free(3)raises ValueError: that block is free already
alloc(2)3
free(8)raises ValueError: 8 is inside the block at 7

Level 2 gives each block an owner, adds release(owner) and free_runs(), and makes the arena 80 GiB, too big for one slot per unit. Level 3 adds aligned blocks and resize, which grows a block in place or reports that it can't.

You don't write it yet. The lesson builds the pieces first: a free list of runs, first fit, the merge on free, and the dicts that track blocks and their owners. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.

This lesson builds on intervals: the free memory is a sorted list of runs, and freeing a block merges it with its neighbors the way the intervals lesson merges ranges.