Design a contiguous segment allocator
Company: Tesla
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's competency in designing and implementing efficient data structures for interval management, contiguous memory allocation, fragmentation handling, tag-based resource tracking, and algorithmic complexity analysis.
Constraints
- 0 <= n (n may be 0, an empty array)
- Each op is ["allocate", len, tag] or ["release", tag]
- allocate with len <= 0 or len > n returns -1 and allocates nothing
- Tags may repeat across allocate calls; release(tag) frees every cell carrying that tag
- release of an absent tag returns 0
- allocate returns the LOWEST feasible start index
Examples
Input: (10, [["allocate", 3, "a"], ["allocate", 2, "b"], ["release", "a"], ["allocate", 4, "c"], ["allocate", 3, "d"]])
Expected Output: [0, 3, 3, 5, 0]
Explanation: a takes [0,2], b takes [3,4]. release a frees 3 cells. allocate 4 'c': [0,3] is blocked by b at 3, so lowest fit is [5,8] -> 5. allocate 3 'd': cells 0,1,2 are free -> 0.
Input: (5, [["allocate", 6, "x"], ["allocate", 0, "y"], ["allocate", 5, "z"], ["allocate", 1, "w"], ["release", "missing"]])
Expected Output: [-1, -1, 0, -1, 0]
Explanation: len 6 > n=5 -> -1. len 0 <= 0 -> -1. z fills [0,4] -> 0. w can't fit (array full) -> -1. releasing a tag that was never allocated -> 0.
Input: (8, [["allocate", 2, "t"], ["allocate", 2, "t"], ["release", "t"]])
Expected Output: [0, 2, 4]
Explanation: Repeated tag: first t -> [0,1] (index 0), second t -> [2,3] (index 2). release t frees all 4 cells carrying 't'.
Input: (4, [["allocate", 2, "a"], ["allocate", 1, "b"], ["allocate", 1, "c"], ["release", "b"], ["allocate", 1, "d"]])
Expected Output: [0, 2, 3, 1, 2]
Explanation: a=[0,1], b=[2], c=[3]. release b frees 1 cell (index 2). allocate 1 'd' takes the now-free lowest cell -> index 2.
Input: (0, [["allocate", 1, "a"], ["release", "a"]])
Expected Output: [-1, 0]
Explanation: Empty array (n=0): any allocate of positive length has len > n -> -1. release of absent tag -> 0.
Input: (6, [["allocate", 6, "full"], ["allocate", 1, "x"], ["release", "full"], ["allocate", 6, "again"]])
Expected Output: [0, -1, 6, 0]
Explanation: full occupies all 6 cells -> 0. x can't fit -> -1. release full frees all 6. allocate 6 'again' now fits the whole array -> 0.
Hints
- allocate must return the lowest index where `len` consecutive cells are all free — think 'first fit', not 'best fit'.
- Guard len <= 0 and len > n up front: both return -1 with no state change.
- Because tags can repeat, releasing must free EVERY cell carrying the tag, not just the most recent block — a tag -> segments map makes release O(segments).
- For O(log n) per op, keep the maximal free intervals in a balanced/ordered structure so you can find the lowest interval of sufficient length, and merge neighbors on release.