Implement a memory allocator with malloc/free
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates understanding of memory allocator concepts including malloc/free semantics, contiguous allocation, fragmentation handling, coalescing of adjacent free blocks, pointer validation, and data-structure choices for efficient allocation.
Constraints
- 1 <= totalSize <= 10^9
- 1 <= len(operations) <= 2 * 10^5
- For ('malloc', size): 1 <= size <= 10^9
- Pointers passed to free may be invalid or already freed
- Memory blocks returned by malloc are always contiguous and non-overlapping
Examples
Input: (10, [('malloc', 3), ('malloc', 4), ('free', 0), ('malloc', 2), ('free', 3), ('malloc', 5)])
Expected Output: [0, 3, True, 0, True, 2]
Explanation: Alloc 3 at 0, alloc 4 at 3, free 0..2, alloc 2 reuses 0..1, free 3..6 which coalesces with remaining free into 2..9, alloc 5 at 2.
Input: (5, [('malloc', 2), ('malloc', 3), ('malloc', 1), ('free', 0), ('free', 0), ('malloc', 1)])
Expected Output: [0, 2, -1, True, False, 0]
Explanation: After allocating 2 and 3 bytes, no space remains. Freeing pointer 0 succeeds once, then fails on double-free. Final malloc(1) uses freed space at 0.