FastPrepFixed-Size Memory Pool

Fixed-Size Memory Pool

Headlands Technologies logoHeadlands Technologies● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Implement a pool containing capacity equal-size blocks. Blocks are represented by integer handles 0 through capacity - 1; handle 0 is valid.

Process the finite operations batch in order:

  • ALLOC removes and returns the first free block. If no block is free, return -1 and leave the pool unchanged.
  • FREE handle releases a currently allocated block and places it at the front of the free list. Every free is valid.

Initially, the free list is [0,1,...,capacity-1]. Released blocks are therefore reused in last-freed-first order, before any blocks still at the back of the free list. Return one integer for each ALLOC, in request order. FREE produces no output entry.

The handles model equal-size slots; no actual process addresses or calls to a system allocator are required.

Function

processMemoryPool(capacity: int, operations: String[]) → int[]

Examples

Example 1

capacity = 3operations = ["ALLOC","ALLOC","FREE 0","FREE 1","ALLOC","ALLOC","ALLOC","ALLOC"]return = [0,1,1,0,2,-1]

The first allocations use0 and1. Freeing0 then1 puts1 before0 in the free list. The remaining untouched block2 is used next; exhaustion returns-1.

Example 2

capacity = 0operations = ["ALLOC","ALLOC"]return = [-1,-1]

A zero-capacity pool cannot allocate. Each failed allocation leaves the empty pool unchanged.

Example 3

capacity = 2operations = []return = []

No allocation request occurs, so no output entries are returned.

Constraints

  • 0 <= capacity <= 10^5.
  • 0 <= operations.length <= 10^5.
  • Each operation is exactly ALLOC or FREE handle, where the handle is a decimal integer in [0,capacity).
  • Every FREE names a currently allocated block; double frees and foreign handles are excluded.
  • One pool is used. All blocks have the same size; alignment, concurrency, multiple block sizes and actual memory addresses are outside this adapter.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int[] processMemoryPool(int capacity, String[] operations) {
    // Write your code here.
}
capacity3
operations["ALLOC","ALLOC","FREE 0","FREE 1","ALLOC","ALLOC","ALLOC","ALLOC"]
expected[0,1,1,0,2,-1]
Checking account…