Sort by start or by end: which one and why

Video lessonComing soon

1 One room, five bookings

A meeting room has five bookings for tomorrow. Each booking is an interval: a start time and an end time, in hours. They come in the order people made them:

[[14, 17], [9, 12], [11, 13],
 [15, 16], [10, 11]]

A day planner is easier to read. It has one column per hour, and each booking fills the hours it uses. The bookings are named A to E in order of start time:

910111213141516AAABCCDDDE
One room, five bookings. Each box is one hour

The box under 10 is the hour from 10 to 11. So A, from 9 to 12, fills the boxes under 9, 10 and 11. Three questions come up about a day like this:

  • Busy hours. When is the room in use? This is Merge Intervals.
  • Clashes. What is the fewest bookings we can cancel so that none clash? This is Non-overlapping Intervals.
  • Rooms. How many rooms would hold every booking? This is Meeting Rooms II.

Checking every pair of bookings is around 10¹⁰ steps at n = 10⁵. That is far past the time limit, so it gets Time Limit Exceeded (TLE). Each question takes one pass after a sort instead, but each needs its own sort key: by start, by end, and starts and ends apart.

2 When two bookings clash

Two intervals overlap when each one starts before the other ends. On the planner, they share a box. A and B share the box under 10, and A and C share the box under 11.

a.start < b.end and b.start < a.end

Both halves matter. A starts before D ends, but D starts at 14, after A has ended. So A and D do not overlap.

Problems disagree about intervals that touch, where one ends at the moment the next starts. B ends at 11 and C starts at 11. On the planner they sit in neighbouring boxes and share none.

  • Merge Intervals joins them. [1, 4] and [4, 5] become [1, 5], because the room is busy from 1 to 5 without a break. The test uses <=.
  • Non-overlapping Intervals and the meeting rooms problems allow them. One meeting ends as the next begins. The test uses <.
  • Minimum platforms counts them as a clash. The leaving train still holds its platform when the next train arrives.

Each problem's examples settle it, so check them before writing the comparison.

3 Sort by start to merge

Merge Intervals joins every group of overlapping intervals into one and returns the groups. For our room, that is the busy hours.

After a sort by start, we read the planner from left to right. We build one group at a time and keep only its end. Each next booking does one of two things:

  • It starts at or before the group's end. It joins, and the group's end becomes the larger of the two ends.
  • It starts after the group's end. The group is finished, and this booking opens a new one.

The second case is why one pass is enough. Every later booking starts even later, so none of them can reach back into a finished group. A gap on the planner is never filled from the right.

Without the sort, that fails. In [[1, 2], [5, 6], [2, 5]], the last interval joins the first two into [1, 6]. A pass in the given order closes [1, 2] before it sees [2, 5], and returns two groups.

In the steps below, the bottom row is the busy time so far:

Merging the bookings, sorted by start
910111213141516AAABCCDDDE
A opens the first group: busy 9 to 12

The same run as a table:

bookingstartendlast groupstart ≤ its end?groups after
A912none–[9, 12]
B1011[9, 12]yes[9, 12]
C1113[9, 12]yes[9, 13]
D1417[9, 13]no[9, 13], [14, 17]
E1516[14, 17]yes[9, 13], [14, 17]

B and E are the rows to watch. Each one sits inside its group and ends before the group does. So the group keeps its own end. Taking the booking's end there would cut the group short.

4 The merge, in code

The code keeps the finished groups in merged. The last one is the group being built, and it changes in place.

C++

true means a goes first. Return a[0] < b[0], never <=, and never a[0] - b[0], because any number other than 0 counts as true. A sort with no comparator also works for merging, since vectors compare by their first value first.

Compare with Integer.compare. a[0] - b[0] looks the same but overflows when the values are far apart, such as −2 × 10⁹ and 2 × 10⁹, and the sort puts them the wrong way round.

A key, not a comparator. The key picks the start. A sort with no key also works for merging, since lists compare by their first value first. Sorting by end needs the key.

Subtraction is safe here. Numbers stay exact far past 10⁹. Without a compare function, sort compares the intervals as text, and [10, 11] comes before [9, 12].

sort.Slice wants true or false. Return intervals[i][0] < intervals[j][0], not a difference. The built-in max needs Go 1.21.

sort_by_key takes the key, so there is no subtraction to overflow. last_mut lends the last group, so the code can change its end in place.

Compare with CompareTo. a[0] - b[0] overflows when the values are far apart, such as −2 × 10⁹ and 2 × 10⁹, and the sort puts them the wrong way round. merged[^1] is the last group.

Cost. The sort takes O(n log n), and the pass looks at each interval once, O(n). At n = 10⁵, that is a few million steps. The groups take O(n) space, plus whatever the sort uses.

5 Sort by end to keep the most

Non-overlapping Intervals asks for the fewest intervals to remove so that the rest do not overlap. Touching is allowed. Removing the fewest is the same as keeping the most.

A greedy pass fits this. We take the bookings in some order, keep each one that fits after the last one kept, and remove each one that clashes.

Sorting by start feels natural, since it worked for merging. But a start time says nothing about how long a booking holds the room. A starts first and holds the room until 12, so it blocks both B and C.

In each step below, the left planner takes the bookings by start, and the right planner takes them by end. Kept bookings are filled, and removed ones are struck out:

Keeping the most: by start against by end
910111213141516AAABCCDDDE
By start: keep A, room free from 12
910111213141516BAAACCEDDD
By end: keep B, room free from 11

By start, A goes first and costs two bookings. By end, B goes first. It frees the room at 11, so C still fits after it. Sorting by end removes 2, and that is the answer.

The rule is to keep the booking that ends first, because it leaves the most of the day free. The exchange argument from the greedy lesson proves it. Take any best plan. Its first booking ends no earlier than the booking that ends first overall. Swapping that booking in frees the room no later, so the rest of the plan still fits, and the count stays the same.

The pass tracks one value, lastEnd, the end of the last booking kept. A booking that starts before lastEnd clashes and is removed:

The booking that ends first is always kept, so the loop starts from the second. The cost is the same as the merge: O(n log n) for the sort and O(n) for the pass, with O(1) extra space besides the sort.

6 Counting rooms: starts and ends apart

Meeting Rooms II asks how many rooms would hold every booking. A room is busy while its booking runs, so the answer is the most bookings running at once. On the planner, that is the fullest column:

910111213141516AAABCCDDDE12210121
Bookings in use each hour. The most at once is 2

That count is the difference array again: +1 where a booking starts, −1 where it ends, and a running sum. But times can go up to 10⁹, too many for a box each. The count changes only at a start or an end, so we visit only those moments.

This is a sweep. We sort the starts as one list and the ends as another, and walk both in time order, as when merging two sorted lists. A start adds 1 to the rooms in use, and an end takes 1 away. We lose track of which end belongs to which booking. That does not matter, because any freed room can take the next booking.

For our day, the starts are 9, 10, 11, 14, 15 and the ends are 11, 12, 13, 16, 17:

timeeventin usemost so far
9start11
10start22
11end12
11start22
12end12
13end02
14start12
15start22

After the last start, the count can only fall, so we stop. The answer is 2.

At 11, B ends as C starts. The end goes first, so C takes B's room. With the start first, the count would reach 3 for a moment, and the answer would come out 3. Minimum platforms wants the opposite order: an arrival goes before a departure.

A min-heap of end times gets the same answer: it holds the end of every meeting still running, and a new meeting reuses the room whose meeting ends first. The sweep costs O(n log n) for the two sorts and O(n) for the walk, with O(n) space for the lists.

7 Mistakes and edge cases

  • The wrong test for touching. A merge that joins only when the start is < the group's end returns [[1, 4], [4, 5]] unchanged instead of [[1, 5]]. A removal pass that removes when the start is <= the last end removes 1 from [[1, 2], [2, 3]] instead of 0.
  • Taking the new end instead of the larger end. On our bookings, E sits inside D and cuts that group to 14 to 16. The merge returns [[9, 13], [14, 16]] instead of [[9, 13], [14, 17]].
  • Sorting by start to keep the most. On our bookings, that removes 3 instead of 2, because A blocks B and C.
  • Ties in the sweep the wrong way round. Starts before ends on our day give 3 rooms instead of 2.

8 Which key, for which problem

The sign of this topic is an input of start and end times. The table matches each kind of question to its sort key:

questionsort bytrack
Join the overlaps (Merge Intervals)startend of the last group
Add one to a sorted list (Insert Interval)already by startparts before, inside and after it
Keep the most (Non-overlapping Intervals, Most meetings in one room)endlastEnd
Fewest points that hit every interval (Minimum Number of Arrows to Burst Balloons)endwhere the last arrow went
Any clash at all (Meeting Rooms)startthe previous end
Most at once (Meeting Rooms II, Minimum platforms)starts and ends apartrooms in use
Smallest interval holding each query (Minimum Interval to Include Each Query)start, and the queries tooa heap of the open intervals

Two rules cover most of the table. When intervals join into groups, or we walk the timeline, sort by start. When we choose intervals and each choice should leave the most room, sort by end.

Before coding an interval problem, ask whether it joins intervals or chooses them. Joining sorts by start, and choosing sorts by end. Then check what the examples do with two intervals that touch.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.