Implement Memory Allocation and In-Memory Records
MicrosoftSoftware Engineer · OnsiteLast updated
This problem tests your ability to manage a block of contiguous memory via a free-list and maintain a hierarchical data structure for user records.
Problem Statement
You are tasked with building an in-memory management system that handles both raw byte allocation and user record storage.
Part 1: Memory Allocator
You have a fixed-size byte array of capacity N. Implement a memory allocator using the first-fit strategy. You must support:
allocate(size): Find the first available block ofsizebytes. Return the start index, or -1 if unavailable.free(index): Release the block starting atindex. You must merge contiguous free blocks to prevent fragmentation.
Part 2: User Records
Use your allocator (or a simulated approach) to store user records. Each record contains ID, Name (max 32 bytes), and ManagerID. Records are stored in a flat array, but their relationships form a tree.
add_record(id, name, manager_id): Store a new record.get_subordinates(manager_id): Return a list of all names that report directly or indirectly to the givenmanager_id.
Constraints
N(total bytes) <= 10,000.- Number of records <= 100.
IDandManagerIDare integers.
Example
// Allocate 10 bytes at index 0
// Free index 0
// Add user: ID 1, Name "Alice", ManagerID 0
// Add user: ID 2, Name "Bob", ManagerID 1
// get_subordinates(1) -> ["Bob"]
Edge Cases
- Allocating more than the remaining contiguous block size.
- Freeing an index that was never allocated.
- Handling the root user (ManagerID = 0) in the hierarchy.
Hints
Hint 1
Represent the memory as a list of segments, where each segment tracks its start, size, and status (free or occupied).
Hint 2
For merging free blocks, iterate through the list of segments and combine adjacent segments if both are marked as free.
Hint 3
For hierarchical traversal, store records in a hash map where the key is the `ManagerID` and the value is a list of subordinate `IDs`, then use BFS or DFS to gather all descendants.
Follow-up questions
- How would your allocator change if you implemented a 'best-fit' strategy instead of 'first-fit'?
- What are the performance trade-offs of using a linked list versus an array for tracking memory segments?
- How would you handle thread safety if multiple users attempt to allocate memory simultaneously?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.