Conflicting Appointments (medium)

Problem Statement #

Given an array of intervals representing ‘N’ appointments, find out if a person can attend all the appointments.

Example 1:

Appointments: [[1,4], [2,5], [7,9]]
Output: false
Explanation: Since [1,4] and [2,5] overlap, a person cannot attend both of these appointments.

Example 2:

Appointments: [[6,7], [2,4], [8,12]]
Output: true
Explanation: None of the appointments overlap, therefore a person can attend all of them.

Example 3:

Appointments: [[4,5], [2,3], [3,6]]
Output: false
Explanation: Since [4,5] and [3,6] overlap, a person cannot attend both of these appointments.
 

Try it yourself #

Try solving this question here:

Output

2.265s

Can attend all appointments: false Can attend all appointments: false Can attend all appointments: false

Solution #

The problem follows the Merge Intervals pattern. We can sort all the intervals by start time and then check if any two intervals overlap. A person will not be able to attend all appointments if any two appointments overlap.

Code #

Here is what our algorithm will look like:

Output

2.296s

Can attend all appointments: false Can attend all appointments: true Can attend all appointments: false

Time complexity #

The time complexity of the above algorithm is O(NlogN)O(N*logN), where ‘N’ is the total number of appointments. Though we are iterating the intervals only once, our algorithm will take O(NlogN)O(N * logN) since we need to sort them in the beginning.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N), which we need for sorting. For Java, Arrays.sort() uses Timsort, which needs O(N)O(N) space.


Similar Problems #

Problem 1: Given a list of appointments, find all the conflicting appointments.

Example:

Appointments: [[4,5], [2,3], [3,6], [5,7], [7,8]]
Output: 
[4,5] and [3,6] conflict. 
[3,6] and [5,7] conflict.
 
Mark as Completed
←    Back
Intervals Intersection (medium)
Next    →
Problem Challenge 1