Skip to content

Instantly share code, notes, and snippets.

@yavor87
Created January 20, 2026 21:46
Show Gist options
  • Select an option

  • Save yavor87/7208bc818b1dccb698936b0076ee3f44 to your computer and use it in GitHub Desktop.

Select an option

Save yavor87/7208bc818b1dccb698936b0076ee3f44 to your computer and use it in GitHub Desktop.
public class Program
{
public static void Main(string[] args)
{
var input = new List<(int, int)>()
{
(1, 3),
(8, 10),
(2, 6),
(15, 18)
};
var output = MergeIntervalsLinq(input);
}
public static List<(int Start, int End)> MergeIntervalsLinq(List<(int Start, int End)> intervals)
{
if (intervals.Count == 0)
return [];
return intervals
.OrderBy(i => i.Start) // Sort by start time
.Aggregate(
new List<(int Start, int End)>(), // Seed: empty result list
(merged, current) =>
{
if (merged.Count == 0 || merged[^1].End < current.Start)
{
// No overlap — add new interval
merged.Add(current);
}
else
{
// Overlap — extend the last interval
var last = merged[^1];
merged[^1] = (last.Start, Math.Max(last.End, current.End));
}
return merged;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment