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

Python interval capacity sweep: process ends before starts

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A sweep over half-open intervals counts simultaneous reservations when end events precede starts at one timestamp.

Download Python source kit

Operation contract

One loading-dock reservation ends at the instant another begins; [start, end) semantics say they do not overlap. Encode starts as +1 and ends as -1. Sorting the pair (time, change) processes -1 before +1 on a tie. Pairwise overlap checks answer whether two bookings conflict; this sweep finds the peak across all bookings.

Failure and ownership boundary

Reject an interval whose end is not greater than its start. Normalize time zones before sorting real timestamps; datetime rules affect the ordering. A peak count tells how many docks are needed, not which dock each reservation receives.

Working program

python
reservations = [(9, 14), (14, 17), (12, 16)]
events = []
for start, end in reservations:
    if end <= start:
        raise ValueError("empty or reversed reservation")
    events.extend(((start, 1), (end, -1)))

active = 0
peak = 0
for _, change in sorted(events):
    active += change
    peak = max(peak, active)
print("peak docks:", peak)

Output

Output
peak docks: 2

Costs and limits

Sorting 2n events takes O(n log n) time and O(n) storage. Online updates need a different ordered structure.

Common Mistakes

  • Processing starts first makes adjacent half-open intervals look overlapping.
  • Reject zero-length or reversed intervals unless the domain defines them.
  • A peak count is not a resource assignment.

Connected lessons

Python exercise: validate half-open reservations before accepting a batch, Python datetime: require an offset before comparing timestamps, Python sliding-window maximum: retain only useful deque indexes.

python
interval-capacity-sweep
Storage details