KatInterview

Build a Heap Allocator with Fit Policies and Safe Handles

Data Structure DesignModel answer
MediumModel answerData Structure Designmemory-allocatorlinked-listhash-map

Last updated

Design a simulated memory manager over a fixed address range that supports two placement policies, splitting, merging of neighbors, and rejection of stale or forged release requests.

You are asked to build a simulated memory manager. It controls one contiguous range of addresses, 0 through total_size - 1. No real bytes are stored; the manager only tracks which address intervals are in use.

Behavior to implement

Placement policies

  • "FIRST_FIT": among free regions that are big enough (region_size >= requested), pick the one with the lowest start address.
  • "BEST_FIT": among free regions that are big enough, pick the smallest one. If several have the same size, pick the one with the lowest start address.

Splitting. If the chosen region is strictly larger than the request, the low-address part becomes the allocation and the leftover stays free directly after it. An exact fit must not create an empty region.

Merging. When an allocation is released, it must immediately combine with a free region directly before it and/or directly after it, so that two free regions are never adjacent.

Handle safety. allocate returns an opaque integer handle. free must return False, and leave all state untouched, when the handle was never issued, was already released, or refers to an address range that has since been given to a different request.

Interface

class Allocator:
    def __init__(self, total_size: int, strategy: str = "FIRST_FIT"):
        """Manage total_size units of address space using the given policy."""

    def allocate(self, size: int) -> int | None:
        """Return a handle for `size` contiguous units, or None if no free region is large enough."""

    def free(self, handle: int) -> bool:
        """Release the allocation. Return True on success, False if the handle is invalid or stale."""

Constraints

  • 1 <= total_size <= 10^9
  • 1 <= size <= total_size
  • At most 10,000 combined calls to allocate and free
  • strategy is "FIRST_FIT" or "BEST_FIT"

Example

a = Allocator(total_size=100, strategy="FIRST_FIT")

x = a.allocate(30)   # occupies [0, 30)
y = a.allocate(20)   # occupies [30, 50)
z = a.allocate(20)   # occupies [50, 70)

a.free(y)            # True; [30, 50) becomes free
a.free(y)            # False; already released
a.free(99999)        # False; never issued

w = a.allocate(15)   # FIRST_FIT picks [30, 45); [45, 50) stays free
a.free(x)            # frees [0, 30)
a.free(w)            # frees [30, 45); merges with both sides into [0, 50)

What to cover in your answer

  • The data structure you choose and why.
  • How handles are generated and validated.
  • The allocate and free algorithms, including tie-breaking and merging.
  • Time and space complexity, and edge cases you would test.
  • Possible optimizations if the number of operations were much larger.

Hints

Hint 1

Because total_size can reach 10^9, you cannot represent individual bytes. Store intervals (start, size, free-or-used) and keep them ordered by address so that they exactly tile the whole range.

Hint 2

If neighbors in your structure are also the physical neighbors in memory, merging on free is just a few pointer updates. Think about which linked structure gives you that in constant time.

Hint 3

Do not use the start address as the handle. A later allocation can land on the same address and make an old handle look valid. Consider an ever-increasing counter plus a map from handle to block that loses the entry on free.