Sort Ranges Before You Compare Them

Calendars, bookings, shifts, and video timestamps all come as ranges: a start and an end. Questions about ranges sound like they need every range compared against every other one.

Do two meetings clash? Which blocks can be combined? When are two people free at the same time? Comparing all pairs costs O(n²).

Sorting changes the picture. Once the ranges are ordered by start time, a range can only overlap the ones right before it, so a single sweep from left to right answers the question. The sort costs O(n log n), the sweep costs O(n), and the sort is the part that dominates.

The Sweep After the Sort

Here’s the core move. After sorting, keep the end of the latest range you’ve seen, and compare each new start against it:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.