Skip to content

Interval Basics & Sorting

Lesson 1 of 4 · 4 min

Interval Basics & Sorting

Step 1 of 8

Four meetings, drawn in the order they were booked. Each one is just a start and an end.

The Idea

An interval is just a pair: start and end. Two of them overlap when each begins before the other finishes — one test, no special cases.

Checking every pair costs n squared. Sorting by start costs n log n and then guarantees something useful: every interval you meet next starts at or after the one you are holding.

Real-World Example

A shared calendar drawn left to right across the day. Nobody compares Tuesday's fourth meeting with its first — the clashes are visible because the bars are laid out in time order, which is exactly what sorting by start does.

The Code

Your turn

What does this print?

spans = [(5, 8), (1, 4), (1, 2)]
spans.sort()
print(spans[0])

Mini quiz

1 / 3

Two intervals a and b overlap when: