Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
size consecutive free memory units and assign it the id mID.mID.Note that:
mID.mID, even if they were allocated in different blocks.Implement the Allocator class:
Allocator(int n) Initializes an Allocator object with a memory array of size n.int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. 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 id mID. Return the number of memory units you have freed.Example 1:
Input ["Allocator", "allocate", "allocate", "allocate", "freeMemory", "allocate", "allocate", "allocate", "freeMemory", "allocate", "freeMemory"] [[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]] 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. loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0. loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1. loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2. loc.freeMemory(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2. loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3. loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1. loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6. loc.freeMemory(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1. loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1. loc.freeMemory(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
Constraints:
1 <= n, size, mID <= 10001000 calls will be made to allocate and freeMemory.Problem summary: 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 size consecutive free memory units and assign it the id mID. 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 an Allocator object with a memory array of size n. int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. 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 id mID. Return the number of memory units you have freed.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Design
["Allocator","allocate","allocate","allocate","freeMemory","allocate","allocate","allocate","freeMemory","allocate","freeMemory"] [[10],[1,1],[1,2],[1,3],[2],[3,4],[1,1],[1,1],[1],[10,2],[7]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2502: Design Memory Allocator
class Allocator {
private int[] m;
public Allocator(int n) {
m = new int[n];
}
public int allocate(int size, int mID) {
int cnt = 0;
for (int i = 0; i < m.length; ++i) {
if (m[i] > 0) {
cnt = 0;
} else if (++cnt == size) {
Arrays.fill(m, i - size + 1, i + 1, mID);
return i - size + 1;
}
}
return -1;
}
public int freeMemory(int mID) {
int ans = 0;
for (int i = 0; i < m.length; ++i) {
if (m[i] == mID) {
m[i] = 0;
++ans;
}
}
return ans;
}
}
/**
* Your Allocator object will be instantiated and called as such:
* Allocator obj = new Allocator(n);
* int param_1 = obj.allocate(size,mID);
* int param_2 = obj.freeMemory(mID);
*/
// Accepted solution for LeetCode #2502: Design Memory Allocator
type Allocator struct {
m []int
}
func Constructor(n int) Allocator {
return Allocator{m: make([]int, n)}
}
func (this *Allocator) Allocate(size int, mID int) int {
cnt := 0
for i := 0; i < len(this.m); i++ {
if this.m[i] > 0 {
cnt = 0
} else if cnt++; cnt == size {
for j := i - size + 1; j <= i; j++ {
this.m[j] = mID
}
return i - size + 1
}
}
return -1
}
func (this *Allocator) FreeMemory(mID int) int {
ans := 0
for i := 0; i < len(this.m); i++ {
if this.m[i] == mID {
this.m[i] = 0
ans++
}
}
return ans
}
/**
* Your Allocator object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Allocate(size,mID);
* param_2 := obj.FreeMemory(mID);
*/
# Accepted solution for LeetCode #2502: Design Memory Allocator
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)
// Accepted solution for LeetCode #2502: Design Memory Allocator
/**
* [2502] Design Memory Allocator
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
struct Allocator {
memory: Vec<bool>,
id_map: HashMap<i32, Vec<(usize, usize)>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Allocator {
fn new(n: i32) -> Self {
let n = n as usize;
Self {
memory: vec![false; n],
id_map: HashMap::new(),
}
}
fn allocate(&mut self, size: i32, m_id: i32) -> i32 {
let size = size as usize;
let mut start = 0;
while start < self.memory.len() {
let mut pos = start;
while pos < self.memory.len() && !self.memory[pos] {
if pos - start + 1 == size {
for i in start..=pos {
self.memory[i] = true;
}
let entry = self.id_map.entry(m_id).or_insert(vec![]);
entry.push((start, pos));
return start as i32;
}
pos += 1;
}
// 到达这里只能说明找到的空间不足
start = pos + 1;
}
-1
}
fn free_memory(&mut self, m_id: i32) -> i32 {
if let Some(array) = self.id_map.get(&m_id) {
let mut length = 0;
for &(start, end) in array.iter() {
for i in start..=end {
self.memory[i] = false;
}
length += (end - start + 1) as i32;
}
self.id_map.remove(&m_id);
length
} else {
0
}
}
}
/**
* Your Allocator object will be instantiated and called as such:
* let obj = Allocator::new(n);
* let ret_1: i32 = obj.allocate(size, mID);
* let ret_2: i32 = obj.free_memory(mID);
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2502() {
let mut allocator = Allocator::new(10);
assert_eq!(0, allocator.allocate(1, 1));
assert_eq!(1, allocator.allocate(1, 2));
assert_eq!(2, allocator.allocate(1, 3));
assert_eq!(1, allocator.free_memory(2));
assert_eq!(3, allocator.allocate(3, 4));
assert_eq!(1, allocator.allocate(1, 1));
assert_eq!(6, allocator.allocate(1, 1));
assert_eq!(3, allocator.free_memory(1));
assert_eq!(-1, allocator.allocate(10, 2));
assert_eq!(0, allocator.free_memory(7));
}
}
// Accepted solution for LeetCode #2502: Design Memory Allocator
class Allocator {
private m: number[];
constructor(n: number) {
this.m = Array(n).fill(0);
}
allocate(size: number, mID: number): number {
let cnt = 0;
for (let i = 0; i < this.m.length; i++) {
if (this.m[i] > 0) {
cnt = 0;
} else if (++cnt === size) {
for (let j = i - size + 1; j <= i; j++) {
this.m[j] = mID;
}
return i - size + 1;
}
}
return -1;
}
freeMemory(mID: number): number {
let ans = 0;
for (let i = 0; i < this.m.length; i++) {
if (this.m[i] === mID) {
this.m[i] = 0;
ans++;
}
}
return ans;
}
}
/**
* Your Allocator object will be instantiated and called as such:
* var obj = new Allocator(n)
* var param_1 = obj.allocate(size,mID)
* var param_2 = obj.freeMemory(mID)
*/
Use this to step through a reusable interview workflow for this problem.
Use a simple list or array for storage. Each operation (get, put, remove) requires a linear scan to find the target element — O(n) per operation. Space is O(n) to store the data. The linear search makes this impractical for frequent operations.
Design problems target O(1) amortized per operation by combining data structures (hash map + doubly-linked list for LRU, stack + min-tracking for MinStack). Space is always at least O(n) to store the data. The challenge is achieving constant-time operations through clever structure composition.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.