Contiguous Range Manager with Dynamic Resizing
Data Structure DesignModel answerLast updated
Build a system to manage named, non-overlapping contiguous ranges over a fixed ID space with dynamic resizing that minimally shifts neighbors.
You are building a range manager for a fixed integer ID space spanning [0, 999] (1,000 total IDs). The system tracks named buckets, where each bucket owns a contiguous inclusive range of IDs like [start, end]. Ranges must never overlap, must stay within bounds, and maintain a stable ordering.
Implement a data structure supporting these operations:
1. Initialization from specifications
Support two initialization modes:
-
Size-based packing: Given
[(name, desired_size), ...]in order, assign contiguous ranges by packing buckets from ID 0 upward in the given sequence. Return[(name, start, end), ...]. Reject if total sizes exceed capacity. -
Range validation: Given
[(name, start, end), ...]with proposed ranges, verify they're within[0, 999], non-overlapping, and return them sorted by start position. Gaps between buckets are allowed.
2. Dynamic resizing
Implement resize(name, new_size) that adjusts the named bucket to own exactly new_size IDs while preserving all invariants (contiguous, non-overlapping, in-bounds, ordered):
-
Growing: First consume immediately adjacent free space. If insufficient, shift neighboring ranges minimally to create room. Use a deterministic policy: push right neighbors rightward first, then left neighbors leftward if needed. Each neighbor moves only the minimum distance required.
-
Shrinking: Release IDs back to the free pool by reducing the bucket's size while keeping its start position fixed.
-
Failure: If the request exceeds available capacity (considering total free space across the entire ID range), return an error without modifying any state.
3. Analysis requirements
- Specify your data structures and the time/space complexity for each operation
- Describe test cases covering: empty input, zero-size buckets, full capacity usage, capacity overflow attempts, resizing boundary buckets (first/last), and invalid bucket names
- Explain how you'd handle concurrent resize requests in a multi-threaded environment
Provide working code with clear error handling.
Hints
Hint 1
Store buckets as an ordered list with (name, start, size) to efficiently track gaps between consecutive ranges
Hint 2
When growing, calculate free space on both sides first before attempting any neighbor shifts
Hint 3
Use a copy-on-write approach: compute all changes on a duplicate structure and commit atomically only if the operation succeeds
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifying Requirements
Before implementing, I'd confirm:
- ID boundaries: The space is
[0, 999]inclusive (1,000 IDs) - Zero-size handling: Buckets with size 0 are valid, maintain position but own no IDs (represented as
end = start - 1) - Ordering constraint: Bucket order is immutable; resize never reorders
- Atomicity: Failed operations leave state completely unchanged
- Error handling: All failures raise exceptions with descriptive messages
Core Data Structure
Use an ordered list of buckets stored as (name, start, size) tuples, plus a name-to-index dictionary for O(1) lookups. Since ranges are ordered and disjoint, free space exists only in gaps between consecutive buckets and at the boundaries.
Benefits:
- Gap calculation is simple:
gap_after[i] = buckets[i+1].start - (buckets[i].start + buckets[i].size) - Range queries scan linearly, which is acceptable for n ≤ 1000
- Shifting operations work naturally with list semantics
Implementation Approach
Size-based packing: Walk the specification list once, computing each bucket's start as the sum of all previous sizes. Verify total doesn't exceed 1,000.
Range validation: Sort proposed ranges by start, then verify each consecutive pair satisfies prev.end < next.start with no overlaps or out-of-bounds issues.
Resize logic: The key challenge. For growth by delta IDs:
- Consume right gap: Expand end rightward into adjacent free space
- Consume left gap: Move start leftward into preceding free space
- Push right neighbors: Shift buckets rightward in sequence, each moving only enough to clear overlap with its predecessor
- Push left neighbors: Mirror operation, shifting leftward from the target bucket
Feasibility check: delta <= (total_capacity - sum_of_all_sizes). If this passes, the cascading shifts will always find room.
For shrinking: Simply reduce size while keeping start fixed. Freed IDs become part of the right gap.
Correctness Invariants
After any operation:
- Contiguous: Each bucket is a single
[start, start+size-1]interval - Ordered:
bucket[i].start + bucket[i].size <= bucket[i+1].startfor all i - In-bounds:
0 <= startandstart + size <= 1000 - Minimal movement: Each neighbor shifts only by the exact overlap amount; cascades stop when a bucket doesn't need to move
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Size-based init | O(n) | O(n) |
| Range validation | O(n log n) | O(n) |
| Resize | O(n) | O(n) |
| Layout query | O(n) | O(n) |
Where n is the number of buckets. The resize copies the entire structure and may cascade through all buckets in worst case.
Optimization opportunity: For high-frequency resizes, use an undo log instead of full copy, or maintain a segment tree over bucket sizes for O(log n) prefix sums.
Edge Cases & Testing
Boundary conditions:
- Empty bucket list (all 1,000 IDs free)
- Single bucket at capacity (no free space)
- Zero-size buckets (grow from 0, shrink to 0)
- First bucket resize (no left neighbor)
- Last bucket resize (no right neighbor)
Error conditions:
- Total size exceeding 1,000
- Growth request larger than available free space
- Invalid bucket name
- Negative sizes
- Duplicate names
- Overlapping or out-of-bounds proposed ranges
Property-based tests: After random resize sequences, verify invariants hold and that failed operations leave state byte-identical.
Concurrency Handling
Three approaches:
-
Coarse locking: Single mutex protecting entire structure. Simple but limits throughput. Suitable for low contention.
-
Optimistic concurrency: Attach version number to state. Each resize reads current version, computes changes, then commits via compare-and-swap. Retry on conflict. Works well when conflicts are rare.
-
Serialized queue: Funnel all resize requests through a single-threaded worker with a command queue. Provides deterministic ordering and simplifies reasoning about state.
For most systems, coarse locking or a serialized worker is preferable—the complexity of fine-grained synchronization isn't justified for an operation that's O(n) anyway.
Python Implementation
class RangeManagerError(Exception):
pass
class RangeManager:
TOTAL_IDS = 1000
def __init__(self, buckets=None):
self._buckets = buckets or []
self._name_index = {name: i for i, (name, _, _) in enumerate(self._buckets)}
@classmethod
def from_sizes(cls, specs):
"""Initialize by packing sizes sequentially from ID 0."""
names_seen = set()
buckets = []
position = 0
for name, size in specs:
if name in names_seen:
raise RangeManagerError(f"Duplicate name: {name}")
if size < 0:
raise RangeManagerError(f"Invalid size {size} for {name}")
names_seen.add(name)
buckets.append([name, position, size])
position += size
if position > cls.TOTAL_IDS:
raise RangeManagerError(f"Total size {position} exceeds {cls.TOTAL_IDS}")
return cls(buckets)
@classmethod
def from_ranges(cls, specs):
"""Initialize from proposed ranges; verify and sort."""
if len(specs) != len(set(s[0] for s in specs)):
raise RangeManagerError("Duplicate bucket names")
for name, start, end in specs:
if not (0 <= start <= end < cls.TOTAL_IDS):
raise RangeManagerError(f"Range [{start}, {end}] out of bounds for {name}")
sorted_specs = sorted(specs, key=lambda x: x[1])
for i in range(len(sorted_specs) - 1):
_, _, end1 = sorted_specs[i]
_, start2, _ = sorted_specs[i + 1]
if end1 >= start2:
raise RangeManagerError("Overlapping ranges detected")
buckets = [[name, start, end - start + 1] for name, start, end in sorted_specs]
return cls(buckets)
def get_layout(self):
"""Return current allocation as [(name, start, end), ...]."""
return [(n, s, s + sz - 1) for n, s, sz in self._buckets]
def resize(self, name, new_size):
"""Adjust bucket to new_size, shifting neighbors minimally."""
if name not in self._name_index:
raise RangeManagerError(f"Unknown bucket: {name}")
if new_size < 0:
raise RangeManagerError(f"Invalid size: {new_size}")
work = [list(b) for b in self._buckets]
idx = self._name_index[name]
current_size = work[idx][2]
delta = new_size - current_size
if delta == 0:
return
total_used = sum(b[2] for b in work)
if delta > self.TOTAL_IDS - total_used:
raise RangeManagerError("Insufficient capacity")
if delta < 0:
work[idx][2] = new_size
self._commit(work)
return
# Growth: try gaps first, then cascade
start = work[idx][1]
right_gap = (work[idx + 1][1] - (start + current_size)) if idx + 1 < len(work) else (self.TOTAL_IDS - (start + current_size))
left_gap = (start - (work[idx - 1][1] + work[idx - 1][2])) if idx > 0 else start
from_right = min(delta, right_gap)
remaining = delta - from_right
from_left = min(remaining, left_gap)
remaining -= from_left
work[idx][1] -= from_left
work[idx][2] = new_size
if remaining > 0:
self._push_right(work, idx, remaining)
self._commit(work)
def _push_right(self, buckets, start_idx, needed):
"""Cascade buckets rightward to create space."""
end_pos = buckets[start_idx][1] + buckets[start_idx][2]
for i in range(start_idx + 1, len(buckets)):
if buckets[i][1] >= end_pos:
break
shift = end_pos - buckets[i][1]
buckets[i][1] = end_pos
end_pos = buckets[i][1] + buckets[i][2]
def _commit(self, new_buckets):
"""Atomically update state."""
self._buckets = new_buckets
self._name_index = {name: i for i, (name, _, _) in enumerate(new_buckets)}
This solution provides clean separation of concerns, predictable behavior under all edge cases, and a foundation for production hardening with concurrency controls.