KatInterview

Contiguous Block Allocator with Tag-Based Memory Management

Data Structure DesignAuto-graded · 21 test cases
MediumAuto-gradedData Structure Designsegment-treeinterval-managementdata-structure-design

Last updated

Tests segment tree design for efficiently finding and tracking contiguous free blocks in a memory-like array with logarithmic-time allocation and release operations.

You need to implement a memory allocator that manages n cells in a linear array (indexed 0 through n-1). Initially, all cells are free.

Your allocator must support two operations through a sequence of commands:

  1. allocate(length, tag): Find the smallest index i where cells [i, i+length-1] are all free. Mark those cells with the given identifier tag and return i. If no contiguous block of that size exists, return -1.

  2. release(tag): Free all cells currently marked with the identifier tag and return the count of cells freed. If the tag doesn't exist or has no allocated cells, return 0.

Implement a function that processes a sequence of these operations and returns a list of results (one integer per operation).

Important behaviors:

  • Multiple allocate calls with the same tag accumulate cells under that tag
  • A single release frees all cells owned by that tag
  • allocate always chooses the lowest valid starting index
  • Invalid lengths (length <= 0 or length > n) immediately return -1
  • Fragmentation may prevent allocation even when total free cells exceed the requested length

Constraints:

  • 0 <= n <= 100,000
  • 1 <= number of operations <= 10,000
  • 1 <= length <= n for valid allocations
  • 1 <= tag <= 10^9
  • All operations are either "allocate" or "release"

Examples

Example 1

Input: block_allocator(10, ['allocate', 'allocate', 'release', 'allocate'], [[3, 1], [2, 2], [1], [4, 3]])

Output: [0, 3, 3, 5]

Example 2

Input: block_allocator(5, ['allocate', 'allocate', 'release', 'release'], [[2, 7], [2, 7], [7], [99]])

Output: [0, 2, 4, 0]

Example 3

Input: block_allocator(4, ['allocate', 'allocate', 'allocate', 'release'], [[0, 1], [5, 2], [2, 3], [3]])

Output: [-1, -1, 0, 2]

Hints

Hint 1

Use a segment tree where each node tracks the longest free prefix, suffix, and interior run within its range to enable O(log n) searches.

Hint 2

When searching for a block, check the left subtree first, then runs crossing the midpoint, then the right subtree to guarantee the lowest starting index.

Hint 3

Store a map from each tag to the set of cell indices it owns to handle release operations and allow tags to accumulate multiple allocations.