Interview question
Merge overlapping time ranges
Implements interval merging for scheduling-style time ranges with sorted output.
TL;DR
Implements interval merging for scheduling-style time ranges with sorted output.
Sorting, interval merging, edge cases, inclusive/exclusive boundary decisions, and readable implementation.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement MergeRanges(IEnumerable<TimeRange> ranges). A range has Start and End. Merge ranges that overlap or touch, and return sorted merged ranges. Treat End < Start as invalid input.
Input: [09:00-10:00], [09:30-11:00], [12:00-13:00], [11:00-12:00]
Output: [09:00-13:00]
ArgumentException.10:00-11:00 and 11:00-12:00, merge.I would validate ranges first, sort by start time, then walk once while tracking the current merged range. If the next range starts before or exactly at the current end, I extend the current end. Otherwise I add the current range to the result and start a new one. I would clarify whether touching ranges merge because that boundary rule changes the condition.
public sealed record TimeRange(DateTime Start, DateTime End);
public static IReadOnlyList<TimeRange> MergeRanges(IEnumerable<TimeRange>? ranges)
{
if (ranges is null)
{
return Array.Empty<TimeRange>();
}
var ordered = ranges
.Select(range =>
{
if (range.End < range.Start)
{
throw new ArgumentException("Range end cannot be before start.");
}
return range;
})
.OrderBy(range => range.Start)
.ToList();
if (ordered.Count == 0)
{
return ordered;
}
var result = new List<TimeRange>();
var current = ordered[0];
foreach (var next in ordered.Skip(1))
{
if (next.Start <= current.End)
{
current = current with { End = next.End > current.End ? next.End : current.End };
continue;
}
result.Add(current);
current = next;
}
result.Add(current);
return result;
}
Sorting costs O(n log n), and the merge pass is O(n). Space is O(n) for the sorted list and result.
09-17 and 10-11.No explicit flow link is set yet, so these are nearby drills from the same path or taxonomy.