Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python exercise: merge overlapping half-open reservations

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A half-open interval includes its start and excludes its end, so intervals meeting at one boundary do not overlap.

Download Python source kit

Operation contract

The fixture merges sorted valid reservations only when the next start is strictly before the current end. The first two ranges overlap and become one; a third begins exactly at the merged end and remains separate. That distinction matters when adjacent bookings are allowed. Empty and reversed ranges are rejected before sorting.

Failure and ownership boundary

The function returns new tuples and leaves the caller input unchanged. It does not attach owners, timezones or permissions to the ranges. Python exercise: validate half-open reservations before accepting a batch, Python weighted interval scheduling: reconstruct the accepted nonoverlapping jobs and Python ZoneInfo: classify unique, repeated and missing local times cover those separate contracts.

Working program

python
def merge_reservations(ranges):
    if type(ranges) is not list or len(ranges) > 100 or any(type(row) is not tuple or len(row) != 2 or any(type(value) is not int for value in row) or not 0 <= row[0] < row[1] <= 1000 for row in ranges):
        raise ValueError("bounded half-open ranges")
    merged = []
    for start, end in sorted(ranges):
        if merged and start < merged[-1][1]:
            merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
        else:
            merged.append((start, end))
    return merged

print(merge_reservations([(0, 3), (2, 5), (5, 7)]))
try:
    merge_reservations([(4, 4)])
except ValueError:
    print("empty range rejected")

Output

Output
[(0, 5), (5, 7)]
empty range rejected

Costs and limits

Sorting n intervals takes O(n log n) time; the result can retain O(n) intervals. For presorted trusted input, the scan is O(n), but this boundary validates and sorts before merging.

Common Mistakes

  • Using start <= end would merge merely adjacent bookings.
  • Reject empty ranges before interpreting their overlap.

Connected lessons

Python exercise: validate half-open reservations before accepting a batch, Python weighted interval scheduling: reconstruct the accepted nonoverlapping jobs, Python ZoneInfo: classify unique, repeated and missing local times.

python
merge-half-open-exercise
Storage details