If you're asked for the most bookings you can keep with no two clashing, sort them by end time and keep each one that starts at or after the end of the last one you kept. You can use the same loop when they ask for the fewest you'd have to cancel, because that's just all of them minus the ones you kept.

def by_end(bookings): kept, last = [], float("-inf") for s, e in sorted(bookings, key=lambda b: b[1]): if s >= last: kept.append((s, e)) last = e return kept 

I'll often ask why someone sorted by end and not by start or by length, and the best answers come with a small case where the other rule goes wrong. Here are the three I'd keep in my head. I checked all of them against a brute force over every subset, so you can trust the counts.

Say you sort by start, and you've got 1 to 10, 2 to 3, 4 to 5 and 6 to 7. You'd grab 1 to 10 first and it blocks the rest, so you keep one. By end you'd keep 2 to 3, 4 to 5 and 6 to 7, so that's three.

Say you take the shortest first, with 1 to 5, 4 to 7 and 6 to 10. The short one's 4 to 7 and it hits both of the others, so again you keep one, where by end you'd keep 1 to 5 and 6 to 10.

The one that catches people out is taking whichever booking clashes with the fewest others, because it sounds like it ought to work.

It took me eleven bookings to break it: 0 to 3 and 9 to 12 twice each, 3 to 6 and 6 to 9 once each, 2 to 5 and 8 to 11 twice each, and a bridge from 5 to 8. The bridge only clashes with 2 of them and all the rest clash with 3 or 4, so that rule picks it first. That kills 3 to 6 and 6 to 9. What's left on the left is the two 0 to 3s and the two 2 to 5s, and they all hit each other, so you only get one from there, and it's the same on the right with 8 to 11 and 9 to 12. So you've got three. By end you'd get 0 to 3, 3 to 6, 6 to 9 and 9 to 12, which is four.

Why the end time is safe

I like the swap argument here because you can say it in an interview in about twenty seconds. Take any best answer you like and swap its first booking for whichever one ends first overall. It can't end any later, so it won't hit anything after it, and you've still got an answer that's just as big. Keep doing that and you'll end up with exactly what the greedy loop gives you.

You pay O(n log n) for the sort and then it's one pass. If you want to click through it, I've got a trace on five bookings (you keep 3 and cancel 2) and the balloon version of the same problem at https://academicquant.co.uk/coding-intervals-choose?utm_source=devto&utm_medium=post&utm_campaign=devto-interval-scheduling-earliest-end