Design Memory Allocator — LeetCode 2502 Python Solution

MediumDesignArrayHash TableSimulation
Problem
#2502
Pattern
Hash Map
Reading time
6 min

The problem

You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free.

Example

Input
["Allocator", "allocate", "allocate", "allocate", "freeMemory", "allocate", "allocate", "allocate", "freeMemory", "allocate", "freeMemory"]
Output
[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0]
Explanation
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.

Python solution

Python
class Allocator:

    def __init__(self, n: int):
        self.m = [0] * n

    def allocate(self, size: int, mID: int) -> int:
        cnt = 0
        for i, v in enumerate(self.m):
            if v:
                cnt = 0
            else:
                cnt += 1
                if cnt == size:
                    self.m[i - size + 1 : i + 1] = [mID] * size
                    return i - size + 1
        return -1

    def freeMemory(self, mID: int) -> int:
        ans = 0
        for i, v in enumerate(self.m):
            if v == mID:
                self.m[i] = 0
                ans += 1
        return ans


# Your Allocator object will be instantiated and called as such:
# obj = Allocator(n)
# param_1 = obj.allocate(size,mID)
# param_2 = obj.freeMemory(mID)

Complexity

MeasureComplexity
TimeO(n \times q)
SpaceO(n), where n and q are the size of the memory space and the number of method calls, respectively auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2502. Design Memory Allocator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2502. Design Memory Allocator?
LeetCode 2502. Design Memory Allocator is rated Medium on LeetCode.
What is the time complexity of LeetCode 2502. Design Memory Allocator?
The Python solution on this page runs in O(n \times q).
What is the space complexity of LeetCode 2502. Design Memory Allocator?
The Python solution on this page uses O(n), where n and q are the size of the memory space and the number of method calls, respectively auxiliary space.
What topics does LeetCode 2502. Design Memory Allocator cover?
LeetCode 2502. Design Memory Allocator is tagged Design, Array, Hash Table and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview