#2502

Design Memory Allocator

Medium
ArrayHash TableDesignSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a data structure to keep track of free memory blocks and their sizes, allowing for efficient allocation and freeing of memory. This reduces the need for repeated scanning of the memory array.

⚙️

Algorithm

3 steps
  1. 1Step 1: Maintain an array to represent memory and a map to track allocated blocks by mID.
  2. 2Step 2: For allocation, check the map for free blocks and allocate the leftmost available block.
  3. 3Step 3: For freeing memory, use the map to find and free all blocks associated with the given mID.
solution.py25 lines
1class Allocator:
2    def __init__(self, n: int):
3        self.memory = [0] * n
4        self.allocations = {}
5
6    def allocate(self, size: int, mID: int) -> int:
7        for i in range(len(self.memory) - size + 1):
8            if all(self.memory[j] == 0 for j in range(i, i + size)):
9                for j in range(i, i + size):
10                    self.memory[j] = mID
11                if mID not in self.allocations:
12                    self.allocations[mID] = []
13                self.allocations[mID].append((i, size))
14                return i
15        return -1
16
17    def freeMemory(self, mID: int) -> int:
18        count = 0
19        if mID in self.allocations:
20            for start, size in self.allocations[mID]:
21                for j in range(start, start + size):
22                    self.memory[j] = 0
23                    count += 1
24            del self.allocations[mID]
25        return count

Complexity note: The time complexity is O(n) for both allocation and freeing because we only need to scan through the memory once per operation, and we maintain a map to track allocations efficiently.

  • 1Efficient memory management requires tracking allocations.
  • 2Using data structures like maps can optimize search and retrieval.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.