Created
January 20, 2026 21:46
-
-
Save yavor87/7208bc818b1dccb698936b0076ee3f44 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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