Leftmost Memory Block Allocator
Learn this problemProblem statement
You are given a binary array memory. A value of 0 means that the corresponding memory unit is free, and a value of 1 means that it is occupied.
Process the two-element rows of queries in order while maintaining the current memory state:
[0, x]allocatesxconsecutive units. Find the smallest start indexssuch that every unit fromsthroughs + x - 1is free. If such a block exists, mark it occupied, assign it the next allocation ID, and outputs. Allocation IDs start at1and increase only after successful allocations. If no block fits, output-1and do not consume an ID.[1, id]erases an active allocation. Free exactly the units owned byidand output the allocation's length. Ifiddoes not exist or has already been erased, output-1.
Units that are occupied in the initial memory array do not belong to any allocation ID and cannot be erased by a query.
Return one output for every query, in the same order as the queries.
Function
processMemoryQueries(memory: int[], queries: int[][]) → int[]Examples
Example 1
memory = [0,0,1,0,0]queries = [[0,2],[0,1],[1,1],[0,2]]return = [0,3,2,0]The first allocation occupies indices 0 and 1 and receives ID 1. The second allocation occupies index 3 and receives ID 2. Erasing ID 1 frees two units. The final allocation then uses the leftmost free block, starting at index 0.
Example 2
memory = [1,0,0]queries = [[1,1],[0,3],[0,2],[1,1],[1,1],[0,3]]return = [-1,-1,1,2,-1,-1]The first erase is invalid because no allocation exists yet. Allocating three units fails because index 0 was initially occupied, so no ID is consumed. Allocating two units succeeds at index 1 with ID 1. Its first erase returns length 2; the repeated erase returns -1. The initial occupied unit remains unavailable, so the final allocation also fails.
Constraints
1 <= memory.length <= 2000memory[i]is0or1.1 <= queries.length <= 2000- Every row in
queriescontains exactly two integers. queries[i][0]is0or1.- For
[0, x],1 <= x <= memory.length. - For
[1, id],1 <= id <= queries.length.