FastPrepOccupy and Clean Memory by Allocation ID

Occupy and Clean Memory by Allocation ID

ZipRecruiter logoZipRecruiter● MediumNEW GRADOA
Learn

Problem statement

You are given a binary array memory, where 0 is free and 1 is initially occupied. Process each row in queries:

  • [0, k]: reserve the first k cells of the leftmost free run having length at least k. A successful allocation receives and returns the next positive allocation ID; failure returns -1 and does not consume an ID.
  • [1, id]: free exactly the cells owned by the active allocation id and return its length. Return -1 for an unknown or already-cleaned ID.

Initially occupied cells belong to no allocation and cannot be cleaned.

Function

processMemoryAllocations(memory: int[], queries: int[][]) → int[]

Examples

Example 1

memory = [0,0,1,0,0]queries = [[0,2],[0,1],[1,1],[0,2]]return = [1,2,2,3]

The successful allocations receive IDs 1, 2, and 3; cleaning ID 1 frees two cells.

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]

Only the two-cell allocation succeeds. Its first cleanup frees two cells; repeated cleanup fails.

Constraints

  • 1 <= memory.length,queries.length <= 2000
  • memory[i] is 0 or 1.
  • Every query has exactly two integers and follows one of the stated forms.

More ZipRecruiter problems

See ZipRecruiter hiring insights
public int[] processMemoryAllocations(int[] memory, int[][] queries) {
    // Write your code here.
}
memory[0,0,1,0,0]
queries[[0,2],[0,1],[1,1],[0,2]]
expected[1,2,2,3]
Checking account…