How to detect whether any intervals overlap in a list of start and end times with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Program

    Function HasOverlap(intervals As List(Of Integer())) As Boolean
        If intervals.Count = 0 Then
            Return True
        End If

        ' Sorting is essential because once intervals are ordered by 
        ' start time, any overlap can only occur between adjacent intervals.
        intervals.Sort(Function(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 i As Integer = 1 To intervals.Count - 1
            If intervals(i)(0) < intervals(i - 1)(1) Then
                Return False ' Overlap found
            End If
        Next

        Return True ' No overlap
    End Function

    Sub Main()
        Dim intervals As New List(Of Integer()) From {
            New Integer() {11, 12},
            New Integer() {5, 9},
            New Integer() {15, 17}
        }

        If HasOverlap(intervals) Then
            Console.WriteLine("There are NO overlapping intervals")
        Else
            Console.WriteLine("There ARE overlapping intervals")
        End If
    End Sub

End Module


' run:
'
' There are NO overlapping intervals
'

 



answered Apr 8 by avibootz

Related questions

...