Clean C# solution

  • 0

    The idea is to sort the array by start and then by end. Then compare the lastMergedInterval end with the current interval start and update the lasteMergedInterval end with the maximum of both the end values. Otherwise, add the currentInterval to the list because it doesn't overlap with the lastMergedInterval.

    public IList<Interval> Merge(IList<Interval> intervals)
                if (intervals == null || intervals.Count == 0)
                    return intervals;
                // Sort the array on the start time.
                intervals = intervals
                                .OrderBy(i => i.start)
                                .ThenBy(i => i.end)
                IList<Interval> mergedIntervals = new List<Interval>{
                foreach (var currentInterval in intervals)
                    Interval lastMergedInterval = mergedIntervals.Last();
                    if (lastMergedInterval.end >= currentInterval.start)
                        lastMergedInterval.end = Math.Max(currentInterval.end, lastMergedInterval.end);
                        // Last and current intervals do not overlap. So, add current interval at last in the list.
                return mergedIntervals;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.