Mid Detailed answer Intervals DSA & Coding Interviews

Explain Merge Intervals.

Short answer: Sort intervals by start. Scan and merge when the next start ≤ current end; otherwise push current and start a new one. O(n log n) from sorting.

Sample solution

C#
int[][] Merge(int[][] intervals) {
    Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
    var res = new List<int[]>();
    foreach (var iv in intervals) {
        if (res.Count == 0 || res[^1][1] < iv[0]) res.Add(iv);
        else res[^1][1] = Math.Max(res[^1][1], iv[1]);
    }
    return res.ToArray();
}

Complexity

Time O(n log n), Space O(n).

Common follow-ups

  • Insert Interval
  • Meeting Rooms II (min rooms / sweep line)
  • Employee Free Time
Sorting by start is non-negotiable — say it before coding.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details