Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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

1 Answer

0 votes
import Foundation

func hasOverlap(_ intervals: [(Int, Int)]) -> Bool {
    if intervals.isEmpty {
        return true
    }

    // Sorting is essential because once intervals are ordered by 
    // start time, any overlap can only occur between adjacent intervals.
    let sorted = intervals.sorted { $0.0 < $1.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 in 1..<sorted.count {
        if sorted[i].0 < sorted[i - 1].1 {
            return false // Overlap found
        }
    }

    return true // No overlap
}

func main() {
    let intervals: [(Int, Int)] = [
        (11, 12),
        (5, 9),
        (15, 17)
    ]

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

main()



/*
run:

There are NO overlapping intervals

*/

 



answered Apr 9 by avibootz

Related questions

...