Intervals
50 / 170IntervalsLesson 4 of 6About 39 min
Keeping the interval that frees you up soonest is provably optimal, and the proof is worth knowing.
Everything so far sorted by start, because the questions were about what connects to what. Now the question changes: given conflicting intervals, keep as many as possible without any two overlapping.
Sorting by start is actively bad here. A single very long interval that starts first would be kept and would block everything after it.
The greedy selection is a sort followed by one pass that does constant work per interval. Give its time and space on n intervals, not counting the input itself.
for start, end in sorted(intervals, key=lambda pair: pair[1]): ... # constant work, and two scalars carriedRead the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.