Problem Description
Design a memory allocator that simulates allocation and freeing operations on a 0-indexed memory array of size n. Initially, all memory units are free. The allocator supports two functions:
- allocate(size, mID): Find the leftmost contiguous block of "size" free memory units and allocate them with the id mID. Return the starting index if successful or -1 if no suitable block exists.
- freeMemory(mID): Free all memory units allocated with id mID and return the count of memory units freed.
Key Insights
- Use a simple simulation with an array representing memory, where 0 indicates a free memory unit.
- For the allocate operation, traverse the array to find a contiguous block of free units of the required size.
- For the freeMemory operation, scan the entire memory array and reset units with the specified mID to 0.
- Given the problem constraints (n, size, mID <= 1000 and at most 1000 operations), an O(n) scan for each operation is efficient enough.
Space and Time Complexity
Time Complexity:
- allocate: O(n) per call in the worst case.
- freeMemory: O(n) per call. Space Complexity:
- O(n) for maintaining the memory array.
Solution
We simulate the memory using an array of length n. For the allocate operation, we iterate through the array to search for a contiguous sequence of free slots (i.e., slots with value 0) of the required size. Once found, we mark those slots with the given mID and return the starting index. If no such block exists, we return -1.
For the freeMemory operation, we iterate over the entire array and whenever we find a slot marked with the given mID, we reset it to 0 (free it) and count the number of slots freed. This count is then returned.
This straightforward simulation approach leverages the small constraint sizes and keeps the implementation simple and easy to understand.