Maintained by Vikas Dulgunde, software engineer
You are handed a set of intervals, each written as a pair [start, end] that covers every point from start through end, endpoints included. Two intervals are considered to clash whenever their ranges meet at all, even if they only share a single endpoint. Concretely, [a, b] and [c, d] clash when a <= d and c <= b.
Your goal is to keep as large a subset as you can in which every pair of kept intervals is mutually clash free, then report how many intervals that subset holds. You do not return the intervals themselves, only the count.
Because the touch case counts as a clash, an interval ending at 5 cannot sit beside one starting at 5; the next interval has to start strictly after the previous one ends. This is the classic activity-selection setup, framed so that shared boundaries are not allowed.
Think of each interval as a meeting that occupies a room for its whole span. You want to book the most meetings into one room without any two of them brushing against each other in time.
Pick [1,2] first. [2,3] starts at 2, which is not strictly after 2, so it clashes and is skipped. [3,4] starts at 3, strictly after 2, so it is kept. That gives 2, and no selection does better because any third interval would touch one already chosen.
All three occupy the exact same span, so at most one can be kept. The other two clash with whichever you pick.
The wide [1,10] swallows the other three, so keeping it limits you to one interval. Drop it instead and keep [2,3], [4,5], [6,7]; each starts strictly after the previous ends, giving 3.
Visible test cases
When you are forced to choose between two intervals that clash, which one leaves the most room for future picks? The one that frees up the timeline soonest.
Sort the intervals by their end value. Then sweep left to right, keeping an interval only when its start sits strictly beyond the end of the last one you kept.
Track a single number, the end of the most recently kept interval. An incoming interval qualifies only if its start is strictly greater than that number, because equal endpoints clash here.
Try every possible subset of intervals, discard any subset that contains a clashing pair, and remember the size of the largest clash-free subset. Correct but hopeless at scale.
Among intervals competing for the same stretch of time, the one that ends earliest blocks the least of the future, so always commit to the available interval with the smallest end. Sorting by end lets a single left-to-right sweep make that choice every step.