VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-n-appointments-find-conflicting-appointments/

⇱ Given n appointments, find all conflicting appointments - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Given n appointments, find all conflicting appointments

Last Updated : 23 Jul, 2025

Given n appointments, find all conflicting appointments. 

Examples:

Input: appointments[] = { {1, 5} {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}
Output: Following are conflicting intervals
[3,7] Conflicts with [1,5]
[2,6] Conflicts with [1,5]
[5,6] Conflicts with [3,7]
[4,100] Conflicts with [1,5]

An appointment is conflicting if it conflicts with any of the previous appointments in the array.

The Easy Way To Go Forward With: The Approach:

      Kind of brute force we traverse over backside of current index and check for overlapping.


Output
[3,7] having Conflict with [5,1]
[2,6] having Conflict with [7,3]
[2,6] having Conflict with [5,1]
[10,15] having Conflict with [6,2]
[10,15] having Conflict with [7,3]
[10,15] having Conflict with [5,1]
[5,6] having Conflict with [6,2]
[5,6] having Conflict with [7,3]
[5,6] having Conflict with [5,1]
[4,100] having Conflict with [6,5]
[4,100] having Conflict with [15,10]
[4,100] having Conflict with [6,2]
[4,100] having Conflict with [7,3]
[4,100] having Conflict with [5,1]

Complexity Analysis:

Time Complexity: O(n^2).
Auxiliary Space: O(n)+O(n),in the worst case.

We strongly recommend to minimize the browser and try this yourself first.

A Simple Solution is to one by one process all appointments from the second appointment to last. For every appointment i, check if it conflicts with i-1, i-2, ... 0. The time complexity of this method is O(n2). 
We can use Interval Tree to solve this problem in O(nLogn) time. Following is a detailed algorithm. 

  1. Create an Interval Tree, initially with the first appointment.
  2. Do following for all other appointments starting from the second one.
    1. Check if the current appointment conflicts with any of the existing  appointments in Interval Tree.  If conflicts, then print the current appointment.  This step can be done O(Logn) time.
    2. Insert the current appointment in Interval Tree. This step also can be done O(Logn) time.

Following is the implementation of the above idea.


Output
Following are conflicting intervals
[3,7] Conflicts with [1,5]
[2,6] Conflicts with [1,5]
[5,6] Conflicts with [3,7]
[4,100] Conflicts with [1,5]

Note that the above implementation uses a simple Binary Search Tree insert operations. Therefore, the time complexity of the above implementation is more than O(nLogn). We can use Red-Black Tree or AVL Tree balancing techniques to make the above implementation O(nLogn).

Auxiliary Space: O(h), Here h is the height of the tree. The extra space is used due to recursion call stack.

Comment
Article Tags: