Leftmost-Fit Block Reservation with Owner Release
Data Structure DesignAuto-graded · 24 test casesLast updated
Simulate a storage pool that reserves the leftmost run of contiguous free cells per request and releases everything an owner holds, using efficient free-run tracking.
A storage pool has total_units cells, numbered 0 to total_units - 1. Every cell is free at the start. You are given a list of requests to handle in order. Each request yields exactly one output number.
There are two request types:
- Reserve
[1, length, owner]: look for the leftmost stretch oflengthcontiguous free cells.- If such a stretch exists, mark all of its cells as held by
ownerand output the index of its first cell. - Otherwise leave the pool unchanged and output
-1.
- If such a stretch exists, mark all of its cells as held by
- Release
[2, owner]: free every cell currently held byownerand output how many cells were freed. Output0if the owner holds no cells.
Return the list of outputs, one per request, in order.
Rules
- "Leftmost" means the stretch whose first cell has the smallest index among all stretches of
lengthcontiguous free cells. A stretch may begin in the middle of a longer free area. Only its starting index matters. - An owner may hold several disjoint stretches at once, acquired through separate reserve requests. A single release frees all of them.
- Reserving for an owner that already holds cells is allowed and leaves its existing cells untouched.
- After a release, the same owner ID may reserve again.
Constraints
1 <= total_units <= 1000001 <= len(requests) <= 100000- Reserve requests have the form
[1, length, owner]with1 <= length <= total_unitsand1 <= owner <= 100000. - Release requests have the form
[2, owner]with1 <= owner <= 100000. - Every output is
-1or an integer in[0, total_units]. - The input sizes are large enough that rescanning the entire pool on every request will be too slow. Aim for roughly logarithmic time per request (amortized over the stretches released).
Examples
Example 1
Input: simulate_leftmost_fit(8, [[1, 3, 1], [1, 2, 2], [1, 2, 3], [2, 2], [1, 3, 4], [1, 2, 5], [2, 1], [1, 4, 6]])
Output: [0, 3, 5, 2, -1, 3, 3, -1]
Example 2
Input: simulate_leftmost_fit(5, [[1, 2, 7], [1, 1, 9], [1, 2, 7], [2, 7], [1, 5, 1]])
Output: [0, 2, 3, 4, -1]
Example 3
Input: simulate_leftmost_fit(1, [[2, 3], [1, 1, 3], [1, 1, 4], [2, 3], [1, 1, 4]])
Output: [0, 0, -1, 1, 0]
Hints
Hint 1
The leftmost stretch of `length` free cells always begins at the start of some maximal free run, specifically the leftmost run whose size is at least `length`. So you only need to track maximal free runs, not individual cells.
Hint 2
Store for each position the size of the maximal free run that starts there (0 if none starts there) in a max segment tree. To find the leftmost run of size at least `length`, descend from the root, going left whenever the left child's maximum is large enough.
Hint 3
On release, return each of the owner's stored stretches to the pool and merge with neighbors. The run to the right begins at `end + 1`, so you can read it from the tree. For the run to the left, keep a dictionary from a run's last index to its first index.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Look at the pool as a set of maximal free runs: contiguous free cells bounded on each side by a held cell or the pool edge. Any stretch of length free cells lies entirely inside one run, and the earliest it can start in that run is the run's first cell. Therefore:
The leftmost fitting stretch begins at the first cell of the leftmost run whose size is at least
length.
This reduces each reserve request to a single query: find the leftmost run with size >= length.
Data structures
- A max segment tree over positions. Leaf
pholds the size of the maximal free run that starts atp, or0if no run starts there. Internal nodes hold the maximum of their children. - A dictionary
end_to_startmapping the last index of each free run to its first index. - A dictionary
heldmapping each owner to a list of(start, length)stretches.
Reserve. If the root value is below length, output -1. Otherwise descend from the root, moving to the left child whenever its maximum is at least length, else to the right. The leaf reached is the start s of the leftmost suitable run. Clear that leaf. If the run was longer than length, the leftover begins at s + length, so set that leaf to the remaining size and update end_to_start for the run's unchanged end. If the fit was exact, delete the end_to_start entry. Record the stretch under the owner and output s.
Release. Pop the owner's stretches (output 0 if none). For each stretch [s, e]:
- Right neighbor: if
e + 1is inside the pool and its leaf is positive, a free run starts there (it must start there, sinceewas held). Absorb it and remove its leaf and itsend_to_startentry. - Left neighbor: if
s - 1is the end of some free run, look up that run's start inend_to_start, and absorb it. - Write the merged run's size at its start leaf and register its end in
end_to_start.
Output the total number of cells freed.
Why it is correct
The invariant is that the tree leaves and end_to_start together describe exactly the current maximal free runs.
- Initially there is one run
[0, n-1]. - A reserve splits a run into a held prefix and an optional free suffix. The suffix is still maximal, since its right boundary is unchanged, and its end stays the same.
- A release turns a held stretch into free cells. Merging with a free right neighbor and a free left neighbor yields one maximal run, so the invariant is restored. Stretches of the same owner are released one at a time, each becoming a registered run, so adjacent stretches coalesce correctly.
The descent returns the leftmost leaf with value >= length, which by the key observation is the correct answer.
Complexity
- Reserve: O(log n).
- Release: O(log n) per stretch freed. Each stretch is created by one reserve and freed at most once, so this is amortized O(log n) per request.
- Total time O(n + m log n) for
mrequests. Space O(n + m).
Reference solution
from typing import List
def simulate_leftmost_fit(total_units: int, requests: List[List[int]]) -> List[int]:
n = total_units
size = 1
while size < n + 1:
size *= 2
tree = [0] * (2 * size) # leaf p = length of the free run starting at p, else 0
def set_value(p, v):
p += size
tree[p] = v
p >>= 1
while p:
a = tree[2 * p]
b = tree[2 * p + 1]
tree[p] = a if a > b else b
p >>= 1
end_to_start = {} # last index of a free run -> its first index
set_value(0, n)
end_to_start[n - 1] = 0
held = {} # owner -> list of (start, length)
out = []
for req in requests:
if req[0] == 1:
need, owner = req[1], req[2]
if tree[1] < need:
out.append(-1)
continue
p = 1
while p < size:
p = 2 * p if tree[2 * p] >= need else 2 * p + 1
start = p - size
run_len = tree[p]
run_end = start + run_len - 1
set_value(start, 0)
if run_len > need:
set_value(start + need, run_len - need)
end_to_start[run_end] = start + need
else:
del end_to_start[run_end]
held.setdefault(owner, []).append((start, need))
out.append(start)
else:
stretches = held.pop(req[1], None)
if not stretches:
out.append(0)
continue
total = 0
for start, ln in stretches:
total += ln
end = start + ln - 1
new_start, new_end = start, end
if end + 1 < n and tree[size + end + 1] > 0:
new_end = end + tree[size + end + 1]
set_value(end + 1, 0)
del end_to_start[new_end]
if start > 0 and (start - 1) in end_to_start:
new_start = end_to_start.pop(start - 1)
set_value(new_start, new_end - new_start + 1)
end_to_start[new_end] = new_start
out.append(total)
return out