5/42
Part 2 of 8 · What an end meansLearn and do

Two half-open intervals overlap when each one starts before the other ends

Most interval questions come down to one test: do two intervals overlap?

# half-open: (start, end)
def overlaps(a, b):
    return a[0] < b[1] and b[0] < a[1]


cases = {
    "apart": ((1, 3), (5, 7)),
    "touching": ((1, 4), (4, 7)),
    "crossing": ((1, 5), (3, 7)),
    "inside": ((3, 5), (1, 7)),
}
for name, (a, b) in cases.items():
    print(name, overlaps(a, b))
apart False
touching False
crossing True
inside True

Here are the four cases on one line of time:

The four cases
apart: a
apart: b False
touching: a
touching: b False
crossing: a
crossing: b True
inside: a
inside: b True
02468

The test comes from its opposite. Two intervals don't overlap exactly when one is over by the time the other starts: a_end <= b_start or b_end <= a_start. Negate both sides and you get the one test. Each interval must start before the other ends.

For closed ends, both < become <=, since sharing an end day is sharing a day.

Both tests assume each interval holds something: start < end for half-open, start <= end for closed. The empty closed (5, 3) passes the closed test against (1, 7).

In the editor, write shifts_overlap(a, b): the overlap test for on-call shifts in closed days, where two shifts that share an end day overlap.