How to detect whether any intervals overlap in a list of start and end times with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static bool HasOverlap(List<int[]> intervals)
    {
        if (intervals.Count == 0) {
            return true;
        }

        // Sorting is essential because once intervals are ordered by 
        // start time, any overlap can only occur between adjacent intervals.
        intervals.Sort((a, b) => a[0].CompareTo(b[0]));
        // (5,9), (11,12), (15,17)

        // (5,9) and (11,12) → 11 < 9? No
        // (11,12) and (15,17) → 15 < 12? No

        // The loop compares each interval with the one before it.
        for (int i = 1; i < intervals.Count; i++) {
            if (intervals[i][0] < intervals[i - 1][1]) {
                return false; // Overlap found
            }
        }

        return true; // No overlap
    }

    static void Main()
    {
        var intervals = new List<int[]>
        {
            new int[] {11, 12},
            new int[] {5, 9},
            new int[] {15, 17}
        };

        if (HasOverlap(intervals))
            Console.WriteLine("There are NO overlapping intervals");
        else
            Console.WriteLine("There ARE overlapping intervals");
    }
}



/*
run:

There are NO overlapping intervals

*/

 



answered Apr 8 by avibootz

Related questions

...