Skip to content
CodeItRaw
Sorting

Lesson 5/5

An interval is two numbers: a start and an end (a meeting, a booking). Nearly every question about intervals begins with the same step: sort by start. After sorting, an interval either clashes with the one just before it or it does not; there is no need to look further away.

ordered = sorted(intervals)
blocks = [ordered[0][:]]
for start, end in ordered[1:]:
if start <= blocks[-1][1]:
blocks[-1][1] = max(blocks[-1][1], end)
else:
blocks.append([start, end])
Merging overlapping intervals: if the new interval starts before the last block ends (or at that very moment) it extends the block; otherwise it opens a new one. The max is essential: a short interval inside must not pull the block's end back.

"Is there a clash?" is a simpler form of this: in the sorted list, an interval that starts before the previous one ends is a clash. Sorting a list of pairs looks at the start first by itself, and at the end on a tie.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Calendar Clash

    Function

  2. 02

    Merge Intervals

    Function

  3. 03

    Calendar Blocks

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list