Skip to main content

Given a list of GPU booking slots as start and end hours, merge the slots that overlap. For example, 9 to 10, 9.5 to 11 and 13 to 14 becomes 9 to 11 and 13 to 14.

Coding rounds · Intermediate 1

Short answer

Sort the intervals by start time, then walk through them once. If the current start is at or before the end of the last merged interval, extend that end with max. Otherwise start a new interval. Sorting makes it O(n log n) time; the output takes O(n) memory.

Deeper answer

First clarify the input. Ask whether the list is already sorted, whether intervals that only touch, such as 1 to 2 and 2 to 3, count as overlapping, and whether an interval can have its end before its start.

The steps are: sort with sorted(intervals), which orders by start. Keep a merged list. For each start and end, check start <= merged[-1][1]. When it is true, the two overlap, so set merged[-1][1] = max(merged[-1][1], end). When it is false, or merged is empty, append [start, end]. The max matters because one interval can sit fully inside another, such as 1 to 10 and 2 to 3.

The sort costs O(n log n) and the pass is O(n). Test an empty list, a single interval, a contained interval, touching intervals and unsorted input. Say that you would change <= to < if touching slots should stay separate, and that you build new pairs so the caller's list is not changed.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Write your own functions

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.