Loading
Loading
Sort by start, then decide overlap against one running interval.
Once intervals are ordered by start point, any interval that overlaps the one you are building must begin before that one ends. This reduces a pairwise comparison to a single sweep in which you either extend the current interval or close it and begin a new one.
Sorting by start converts a two-dimensional comparison into a one-dimensional sweep. After sorting, the only question per interval is whether it begins before the current one ends.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def merge(intervals): if not intervals: return [] intervals.sort(key=lambda pair: pair[0]) merged = [list(intervals[0])] for start, end in intervals[1:]: last = merged[-1] if start <= last[1]: # Overlap. Extend, but never shrink: the current interval may # already reach further than this one does. last[1] = max(last[1], end) else: merged.append([start, end]) return merged def max_concurrent(intervals): """Sweep line: +1 at each start, -1 at each end.""" events = [] for start, end in intervals: events.append((start, 1)) events.append((end, -1)) # Ends sort before starts at the same instant, so a meeting ending as # another begins does not count as an overlap. events.sort(key=lambda e: (e[0], e[1])) active = best = 0 for _time, delta in events: active += delta best = max(best, active) return best| Status | Problem | Difficulty | Role |
|---|---|---|---|
| One Calendar, No Clashes#75 | Easy | Primary | |
| Consolidate Booked Slots#78 | Medium | Primary | |
| Slot In a New Booking#79 | Medium | Primary | |
| Shared Free Windows#80 | Medium | Related | |
| Fewest Darts for the Banners#81 | Medium | Related | |
| How Many Studios?#83 | Medium | Primary | |
| Split the Parade#85 | Medium | Related | |
| Fewest Sprinklers for the Lawn#89 | Hard | Related |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in