Leftmost Memory Block Allocator
Learn this problemProblem statement
You are given an integer array memory containing only 0s and 1s. A value of 0 means that the memory unit is free, while 1 means that it is occupied.
Process the two-element arrays in queries in order. Each query has one of two forms:
[0, x]is an allocation query. Find the smallest index that begins a contiguous block ofxfree units. If a block exists, mark all of its units as occupied, assign the next allocation ID to the block, and return its starting index. Allocation IDs start at1and increase only after successful allocations. If no block fits, return-1.[1, id]is an erase query. If an active allocation has IDid, free every unit in that block and return its length. If the ID does not exist or has already been erased, return-1.
Memory units that are occupied initially are not associated with an allocation ID and cannot be freed by an erase query.
Return an integer array containing one result for every query.
Function
processMemoryQueries(memory: int[], queries: int[][]) → int[]Examples
Example 1
memory = [0,0,1,0,0,0]queries = [[0,2],[0,3],[1,1],[0,3]]return = [0,3,2,-1]The first allocation takes indices 0 and 1 with ID 1. The second takes indices 3 through 5 with ID 2. Erasing ID 1 frees two units. No three-unit free block remains for the final query.
Example 2
memory = [0,0,0,0]queries = [[1,1],[0,2],[1,1],[1,1]]return = [-1,0,2,-1]The first erase fails because no allocation exists. The allocation then creates ID 1 at index 0. Its first erase frees two units, while the repeated erase returns -1.
Example 3
memory = [1,0,0,0,1,0,0]queries = [[0,3],[0,2],[1,1],[0,2]]return = [1,5,3,1]The first two allocations use starts 1 and 5. Erasing ID 1 frees its three-unit block, so the final allocation returns the newly available leftmost start 1.
Constraints
1 <= memory.length- Every value of
memoryis0or1. 1 <= queries.length- Every query contains exactly two integers.
queries[i][0]is0or1.1 <= queries[i][1]
More Tiktok problems
- Concatenate Digit-wise SumsOA · Seen Aug 2026
- Count 2x2 Submatrices by Black CellsOA · Seen Aug 2026
- Count House Segments After DestructionOA · Seen Aug 2026
- Debugger Breakpoint ActionsOA · Seen Aug 2026
- Distribution Center Package AllocationOA · Seen Aug 2026
- Find All Local PeaksOA · Seen Aug 2026
- Minimum Height Difference Between Distant PeaksOA · Seen Aug 2026
- Minimum Operations for Stepwise StructuresOA · Seen Aug 2026