Rubrik | Senior Software Engineer | 3.5 yrs | Phone Interview | Reject

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2025-03-15Added By Anonymous
Source: Link

Question:

Implement alloc and free if you are given a 16GB memory:

int alloc(size_t size); // Assign memmory and return index.

free(int index); // Free up the memory assigned at the given index.


Experience:

The interviewer was helpful all along, guiding me in the right direction.


Approach 1:

I proposed a solution which maintained start and end indexes of memory blocks assigned. They did not like it because of linear time complexity of both alloc and free.


Approach 2:

I proposed another approach which allocated memory block of fixed size and realized the inefficiency of it. What would be the size of each block. What if the user requests a size way smaller than the block size.


Approach 3:

The interviewer finally gave me the approach they had in mind :-

1.Divide the entire memory block into sizes of power of 2.
2.Imaginge a tree structure, starting at the root, with the entire 16 GB memory assiged to the head. If the alloc requests for 3GB, we divide the head node into two child nodes, each of 8 GB. We further divide the left 8GB node (since 3GB < 8GB), into child nodes, each of size 4 GB. We end up allocating the left 4GB node.
3.Free then runs through the tree using DFS, frees up the right node and merges nodes if needed.


Neat and efficient way with log n complexity.

With 20 mins on the clock, I code two classes, MemoryNode with properties like size, left node, right node and bool isFull, and Memory class with property head. My alloc function was a DFS like approach, going down the tree to find the right node. However, I was confused with the index which alloc had to return. All in all, I could not come up with a coherent algorithm.

After verbally discussing the free algorithm they ended the interview.


Outcome:

Got rejected within an hour.

Turns out the question is based on a famous algorithm called Buddy Memory Allocator. I wish I had known about this. Nonetheless, it was a good discussion.

Comments