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

1 Answer

0 votes
fun hasOverlap(intervals: List<Pair<Int, Int>>): Boolean {
    if (intervals.isEmpty()) {
        return true
    }

    // Sorting is essential because once intervals are ordered by 
    // start time, any overlap can only occur between adjacent intervals.
    val sorted = intervals.sortedBy { it.first }
    // (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 in 1 until sorted.size) {
        if (sorted[i].first < sorted[i - 1].second) {
            return false // Overlap found
        }
    }

    return true // No overlap
}

fun main() {
    val intervals = listOf(
        11 to 12,
        5 to 9,
        15 to 17
    )

    if (hasOverlap(intervals))
        println("There are NO overlapping intervals")
    else
        println("There ARE overlapping intervals")
}


/*
run:

There are NO overlapping intervals

*/

 



answered Apr 9 by avibootz

Related questions

...