Merge overlapping intervals
Merge all overlapping closed intervals and return the smallest equivalent set of non-overlapping intervals.
Course progress
Problem 42 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected output
1-6, 8-10, 15-18
What is happening?
[1,3] overlaps [2,6], so they combine into [1,6]. The remaining intervals do not overlap and stay separate.
Solution strategy
Build the right mental model
Sort intervals by start value. Extend the last merged interval when the next one overlaps; otherwise append a new interval.
Core concepts
sorting · intervals
Complexity
Time O(n log n), space O(n) for the result.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for merge-overlapping-intervals
using System;
using System.Collections.Generic;
class Program
{
class Interval
{
public int Start { get; set; }
public int End { get; set; }
public Interval(int start, int end) { Start = start; End = end; }
}
static List<Interval> MergeIntervals(List<Interval> intervals)
{
intervals.Sort((first, second) => first.Start.CompareTo(second.Start));
var merged = new List<Interval>();
foreach (Interval interval in intervals)
{
if (merged.Count == 0 || merged[merged.Count - 1].End < interval.Start)
merged.Add(new Interval(interval.Start, interval.End));
else
merged[merged.Count - 1].End = Math.Max(merged[merged.Count - 1].End, interval.End);
}
return merged;
}
static void Main()
{
var intervals = new List<Interval>
{
new Interval(1, 3), new Interval(2, 6),
new Interval(8, 10), new Interval(15, 18)
};
var labels = new List<string>();
foreach (Interval interval in MergeIntervals(intervals))
labels.Add(interval.Start + "-" + interval.End);
Console.WriteLine(string.Join(", ", labels));
}
}Knowledge check
Questions students often ask
What is the main idea behind merge overlapping intervals?
Sort intervals by start value. Extend the last merged interval when the next one overlaps; otherwise append a new interval.
What is the time and space complexity of this solution?
Time O(n log n), space O(n) for the result.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.