Problem · Array

Leftmost Memory Block Allocator

Learn this problem
MediumCapital One logoCapital OneINTERNOA

Problem 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] allocates x consecutive units. Find the smallest start index s such that every unit from s through s + x - 1 is free. If such a block exists, mark it occupied, assign it the next allocation ID, and output s. Allocation IDs start at 1 and increase only after successful allocations. If no block fits, output -1 and do not consume an ID.
  • [1, id] erases an active allocation. Free exactly the units owned by id and output the allocation's length. If id does 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 <= 2000
  • memory[i] is 0 or 1.
  • 1 <= queries.length <= 2000
  • Every row in queries contains exactly two integers.
  • queries[i][0] is 0 or 1.
  • For [0, x], 1 <= x <= memory.length.
  • For [1, id], 1 <= id <= queries.length.

More Capital One problems

drafts saved locally
public int[] processMemoryQueries(int[] memory, int[][] queries) {
    // Write your code here.
}
memory[0,0,1,0,0]
queries[[0,2],[0,1],[1,1],[0,2]]
expected[0,3,2,0]
checking account