KatInterview

Contiguous Range Manager with Dynamic Resizing

Data Structure DesignModel answer
MediumModel answerData Structure Designrange-managementgreedyarray

Last 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