Aligned Memory Allocator
Memory is an array of cells, 0 for free and 1 for occupied. Process a list of queries against it and return one result per query.
[0, x]alloc: find the leftmost block ofxconsecutive free cells whose starting index is a multiple of 8. Mark the block occupied and return its starting index. Each successful alloc is given the next id, counting from 1. If no block fits, return-1(and no id is used).[1, id]erase: free every cell of the block that alloc numberidcreated and return how many cells were freed. If that id was never issued, or its block has already been erased, return-1.
Cells that are occupied in the initial array belong to no id and are never freed.
memory = [0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0] queries = [[0, 3], [0, 6], [0, 2], [1, 1], [0, 4], [1, 9]] result = [0, 16, -1, 3, 0, -1]
The first alloc takes cells 0-2 (id 1). Six cells do not fit after index 0 or at index 8, so the second takes 16-21 (id 2). Nothing aligned is left for two cells. Erasing id 1 frees 3 cells, and the next alloc reuses index 0 (id 3). Id 9 was never issued.
Hints
Hint 1
Only indices 0, 8, 16, ... can start a block, but a block may extend past the next boundary if the cells are free.
Hint 2
Remember, per id, where its block starts and how long it is. Erase then needs no search.
Hint 3
An erased id must answer -1 the second time: delete the record when you erase.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.