Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-266

Memory Pool Freelist Pop/Push

Problem

Simulate a memory pool with a LIFO free list.

num_blocks blocks are initially free as a stack of ids 0 through num_blocks-1. operations contains "alloc" (pop a free block and record its id, or -1 when exhausted), "free" (values[i] is the block id; only currently allocated blocks can be returned), or "in_use" (record the number of allocated blocks).

Return the list of recorded results.

Hint

A LIFO free list returns the most recently freed block first.

Test cases

case 1
in: [3,["alloc","alloc","free","alloc","in_use"],[0,0,1,0,0]]
expected: [2,1,null,1,2]
case 2
in: [2,["alloc","alloc","alloc"],[0,0,0]]
expected: [1,0,-1]
case 3
in: [1,["free","alloc","in_use"],[0,0,0]]
expected: [null,0,1]
case 4
in: [3,["alloc","free","free","alloc"],[0,2,2,0]]
expected: [2,null,null,2]
Starter codePython
def freelist_ops(num_blocks, operations, values):
    # Your code here
    pass

4 test cases · run your code against them in the editor