Skip to content

Intervals

A subscription is a period: it starts, and later it ends. Tasks about periods ask whether two of them overlap, when a customer had access, how many days were covered, or how many subscriptions were active at once. The code is short. The bugs are in the boundaries: a period that ends exactly when the next one starts, a period inside another, an input that is not sorted.

from datetime import datetime
sep = (datetime(2026, 9, 1), datetime(2026, 10, 1))
oct_ = (datetime(2026, 10, 1), datetime(2026, 11, 1))
m = datetime(2026, 10, 1) # midnight between the two months
print(sep[0] <= m < sep[1], oct_[0] <= m < oct_[1]) # False True -- the moment is in one month only
print(sep[1] - sep[0], oct_[1] - oct_[0]) # 30 days, 0:00:00 31 days, 0:00:00

September is [1 September, 1 October). Half-open periods have three useful properties:

  • Each moment belongs to exactly one period. Midnight on 1 October is in October, not in both months.
  • The length is a subtraction. end - start is 30 days for September, with no + 1.
  • Consecutive periods touch without overlapping. A renewal that starts when the previous period ends is not a double subscription.

The practice dataset stores every transaction as [start_time, end_time), and PostgreSQL range types use [) by default. When a task does not say, ask: “Is the end of the period included or excluded?”

Two periods overlap when each one starts before the other one ends. In code, with a and b as the two periods:

from datetime import date
def d(day):
return date(2026, 9, day)
def overlaps(a_start, a_end, b_start, b_end):
return a_start < b_end and b_start < a_end
def overlaps_wrong(a_start, a_end, b_start, b_end):
return a_start <= b_start < a_end or a_start < b_end <= a_end # "an end of b is inside a"
cases = {
"apart": (d(1), d(5), d(10), d(15)),
"touching": (d(1), d(10), d(10), d(15)),
"partial": (d(1), d(10), d(5), d(15)),
"a inside b": (d(5), d(6), d(1), d(30)),
}
for name, c in cases.items():
print(f"{name:<11} {overlaps(*c)!s:<6} {overlaps_wrong(*c)}")
Caseoverlapsoverlaps_wrong
apartFalseFalse
touchingFalseFalse
partialTrueTrue
a inside bTrueFalse

The comparisons are strict (<), because the end is not part of the period: two periods that touch on 10 September share no day. The “wrong” version checks whether an end of b falls inside a. It misses the case where a lies inside b, because then neither end of b is inside a. The two-comparison test covers every case and is easier to say out loud.

The length of the overlap is the earliest end minus the latest start, but never below zero:

from datetime import timedelta
def overlap_days(a_start, a_end, b_start, b_end):
return max(timedelta(0), min(a_end, b_end) - max(a_start, b_start)).days
print(overlap_days(d(1), d(10), d(5), d(15))) # 5 -- 5 to 9 September
print(overlap_days(d(1), d(10), d(10), d(15))) # 0 -- touching
print(overlap_days(d(1), d(5), d(10), d(15))) # 0 -- apart: without max() it would be -5

Merging turns a list of periods that may overlap into a list that does not. It is the answer to “when did the customer have access?”. One pass is enough after a sort:

  1. Sort the periods by start. Tuples sort by their first element, so sorted(periods) is enough.
  2. Keep a current period. If the next one starts no later than the current end, extend the current end to max(current_end, end).
  3. Otherwise there is a gap: close the current period and start a new one.

Here is the trace for five periods in September, given in the order [20, 25), [1, 10), [5, 20), [2, 3), [28, 30):

Next period (sorted)StepCurrent periodResult so far
[1, 10)new[1, 10)[1, 10)
[2, 3)extend[1, 10)[1, 10)
[5, 20)extend[1, 20)[1, 20)
[20, 25)extend[1, 25)[1, 25)
[28, 30)new[28, 30)[1, 25), [28, 30)

[20, 25) touches [1, 20), and this loop merges it, because start <= current_end. For coverage it makes no difference: there is no gap either way. In a list that people read, it may matter, so ask: “Should periods that touch be merged?”

Two bugs are common, and both pass the easy examples:

  • No max(). With current_end = end, the period [2, 3) inside [1, 10) shrinks it: the loop returns [1, 3) for these two periods.
  • No sort. On [20, 25), [1, 10), [5, 20) in the given order, the same loop returns only [20, 25): every later period “overlaps” the first one and never moves its start.

The sort costs O(n log n) and the pass costs O(n). Comparing every pair of periods is O(n²), and it still does not give the merged list.

The total covered time is the sum of the lengths of the merged periods. In the trace above it is [1, 25) plus [28, 30): 24 + 2 = 26 days. Overlaps are counted once, because the merged periods do not overlap.

A related follow-up asks for the largest number of periods active at the same time. The usual answer is a sweep line: +1 at each start, −1 at each end, sort the events, and keep a running count.

def max_active(periods):
events = []
for start, end in periods:
events.append((start, +1))
events.append((end, -1))
events.sort() # at the same moment -1 sorts before +1: an end frees the place first
active = best = 0
for _, delta in events:
active += delta
best = max(best, active)
return best
periods = [(d(1), d(10)), (d(5), d(20)), (d(10), d(15)), (d(12), d(13))]
print(max_active(periods)) # 3 -- on 12 September: [5, 20), [10, 15), [12, 13)
print(max_active([(d(1), d(10)), (d(10), d(15))])) # 1 -- touching periods are never active together

The tie order follows from the half-open rule. If starts came before ends at the same moment, the two touching periods would count as 2.

PythonWrite a functioncore

Do two periods [a_start, a_end) and [b_start, b_end) overlap? Touching ends do not overlap.

Data and an example

The checks run after your code and can use these:

from datetime import date as d

Example: overlaps(d(2026, 9, 1), d(2026, 9, 10), d(2026, 9, 5), d(2026, 9, 20)) → True

3 checks. Your own print() output is shown too.

def overlaps(a_start, a_end, b_start, b_end):
    ...
Show answer

Reference

def overlaps(a_start, a_end, b_start, b_end):
return a_start < b_end and b_start < a_end

Checks and the expected values

  • overlaps(d(2026, 9, 1), d(2026, 9, 10), d(2026, 9, 5), d(2026, 9, 20)) → True
  • overlaps(d(2026, 9, 1), d(2026, 9, 10), d(2026, 9, 10), d(2026, 9, 20)) → False
  • overlaps(d(2026, 9, 5), d(2026, 9, 6), d(2026, 9, 1), d(2026, 9, 30)) → True

Two periods overlap when each one starts before the other one ends: a_start < b_end and b_start < a_end. The comparison is strict because the end is excluded: periods that touch on 10 September do not overlap. The third check is a period inside another, the case that breaks “is an end of b inside a?”.

PythonWrite a function

periods is a list of (start, end) dates, half-open, in any order. Return the total number of days covered by at least one period.

Data and an example

The checks run after your code and can use these:

from datetime import date as d

Example: covered_days([(d(2026, 9, 1), d(2026, 9, 11)), (d(2026, 9, 5), d(2026, 9, 15))]) → 14

4 checks. Your own print() output is shown too.

def covered_days(periods):
    ...
Show answer

Reference

def covered_days(periods):
total = 0
cur_start = cur_end = None
for start, end in sorted(periods):
if cur_end is None or start > cur_end:
if cur_end is not None:
total += (cur_end - cur_start).days
cur_start, cur_end = start, end
else:
cur_end = max(cur_end, end)
if cur_end is not None:
total += (cur_end - cur_start).days
return total

Checks and the expected values

  • covered_days([(d(2026, 9, 1), d(2026, 9, 11)), (d(2026, 9, 5), d(2026, 9, 15))]) → 14
  • covered_days([(d(2026, 9, 1), d(2026, 9, 3)), (d(2026, 9, 3), d(2026, 9, 5)), (d(2026, 9, 10), d(2026, 9, 11))]) → 5
  • covered_days([(d(2026, 9, 20), d(2026, 9, 25)), (d(2026, 9, 1), d(2026, 9, 10)), (d(2026, 9, 2), d(2026, 9, 3)), (d(2026, 9, 5), d(2026, 9, 20))]) → 24
  • covered_days([]) → 0

Sort by start, then one pass: keep the current period and extend it while the next one starts no later than its end; otherwise add its length to the total and start a new one. max(cur_end, end) stops a period inside the current one from shrinking it. The third check is the trace above without [28, 30), in a mixed order: 24 days. Without max() the loop returns 22, and without the sort it returns 5. The empty list must give 0. O(n log n) because of the sort.

PythonWrite a function

periods is a list of (start, end) dates, half-open [start, end), in any order. Return the largest number of periods active at the same moment. A period that ends at the moment another one starts is not active together with it.

Data and an example

The checks run after your code and can use these:

from datetime import date
def sep(day):
return date(2026, 9, day)

Example: max_active([(sep(1), sep(10)), (sep(2), sep(3)), (sep(5), sep(6))]) → 2

4 checks. Your own print() output is shown too.

def max_active(periods):
    ...
Show answer

Reference

def max_active(periods):
events = []
for start, end in periods:
events.append((start, +1))
events.append((end, -1))
events.sort() # at the same moment -1 sorts before +1: an end frees the place first
active = best = 0
for _, delta in events:
active += delta
best = max(best, active)
return best

Checks and the expected values

  • max_active([(sep(1), sep(10)), (sep(2), sep(3)), (sep(5), sep(6))]) → 2
  • max_active([(sep(9), sep(12)), (sep(5), sep(9)), (sep(1), sep(5))]) → 1
  • max_active([(sep(20), sep(25)), (sep(1), sep(30)), (sep(5), sep(8)), (sep(4), sep(10)), (sep(5), sep(6))]) → 4
  • max_active([]) → 0

The sweep line from the section above: +1 at each start, −1 at each end, sort, then keep a running count and its maximum. Tuples sort by time and then by the second element, so at the same moment -1 comes before +1: an end frees its place before the next start takes it. That is the half-open rule. The second check gives three touching periods in reverse order. A sort by time alone (key=lambda e: e[0]) keeps the input order at a tie, puts a start before an end and returns 2. Counting, for each period, the periods that overlap it gives 3 on the first check: [2, 3) and [5, 6) both overlap [1, 10), but not each other. O(n log n) because of the sort.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.