Skip to content

Practice Design Memory Allocator

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2502
LeetCode Problem

Design Memory Allocator

Problem Statement

Allocator(n) starts with n free units indexed from zero. allocate(size,mID) assigns the leftmost contiguous free block of that size and returns its start, or -1 without mutation if none fits. freeMemory(mID) releases all units bearing that ID, across all its blocks, and returns their count. Practice approach: For n at most 1000, scan the array to find a sufficiently long free run. Label accepted cells by ID and scan again to free all matching cells. Each operation is O(n). Total free space is insufficient if fragmented into runs smaller than size.

Source: Design Memory Allocator on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["Allocator","allocate","allocate","allocate","freeMemory","allocate","freeMemory"]
[[6],[2,1],[2,2],[1,1],[1],[3,3],[1]]
Output
[null,0,2,4,3,-1,0]
Explanation

Freeing ID 1 releases two blocks totaling three cells, but their separation prevents a contiguous allocation of three.

Constraints

1 <= n, size, mID <= 1000
At most 1000 total calls.

Related LeetCode Problems

Practice more problems similar to Design Memory Allocator.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.