Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Memory Allocation and Freeing

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Memory Allocation and Freeing. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Implement a simplified memory allocator for a Facebook News Feed service. The allocator manages a contiguous memory array and processes allocation and release commands in order.

Memory is represented by a list of integers where 0 means free and 1 means occupied. An allocation request must receive the first contiguous run of free cells large enough to satisfy the request. Mark the selected cells as occupied and return the starting index. If no suitable run exists, return -1. A release command provides the starting index of a previously successful allocation; free exactly that block.

Implement memory_manager(memory, commands). The function must return one result for every command: an integer starting index for an allocation, or -1 if allocation fails; for a release command, return True after freeing the block.

Each successful allocation is identified by its starting index. The input guarantees that release commands reference currently active allocations and that allocation sizes are positive.

Constraints

  • 1 <= len(memory) <= 10^5
  • Each memory value is either 0 or 1
  • 1 <= len(commands) <= 10^4
  • Allocation sizes are positive integers no greater than len(memory)
  • Release commands reference successful, currently active allocations

Function Signature

def memory_manager(memory, commands):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output