Design Memory Allocator - Problem
You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
- Allocate a block of
sizeconsecutive free memory units and assign it the idmID. - Free all memory units with the given id
mID.
Note that:
- Multiple blocks can be allocated to the same
mID. - You should free all the memory units with
mID, even if they were allocated in different blocks.
Implement the Allocator class:
Allocator(int n)Initializes anAllocatorobject with a memory array of sizen.int allocate(int size, int mID)Find the leftmost block ofsizeconsecutive free memory units and allocate it with the idmID. Return the block's first index. If such a block does not exist, return-1.int freeMemory(int mID)Free all memory units with the idmID. Return the number of memory units you have freed.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["Allocator", "allocate", "allocate", "allocate", "freeMemory"], values = [[10], [1, 1], [1, 2], [1, 3], [2]]
›
Output:
[null, 0, 1, 2, 1]
💡 Note:
Initialize allocator with size 10. allocate(1,1) returns 0 (first position). allocate(1,2) returns 1. allocate(1,3) returns 2. freeMemory(2) frees 1 unit and returns 1.
Example 2 — Failed Allocation
$
Input:
operations = ["Allocator", "allocate", "allocate", "allocate"], values = [[2], [1, 1], [1, 2], [1, 3]]
›
Output:
[null, 0, 1, -1]
💡 Note:
Memory size is 2. First two allocations succeed at positions 0 and 1. Third allocation fails since no free space exists, returns -1.
Example 3 — Multiple Blocks Same ID
$
Input:
operations = ["Allocator", "allocate", "allocate", "freeMemory"], values = [[10], [2, 1], [3, 1], [1]]
›
Output:
[null, 0, 2, 5]
💡 Note:
allocate(2,1) uses positions [0,1]. allocate(3,1) uses positions [2,3,4]. freeMemory(1) frees all 5 positions allocated to mID=1.
Constraints
- 1 ≤ n, size ≤ 1000
- 1 ≤ mID ≤ 1000
- At most 1000 calls will be made to allocate and freeMemory
Visualization
Tap to expand
Understanding the Visualization
1
Input
Memory size n=10, operations: allocate(3,1), allocate(2,2), freeMemory(1)
2
Process
Track memory state and find consecutive free blocks
3
Output
Return starting positions or counts of freed memory
Key Takeaway
🎯 Key Insight: Simulate memory with array, scan linearly for consecutive free blocks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code