VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-interval-completely-overlaps/

⇱ Check if any interval completely overlaps the other - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if any interval completely overlaps the other

Last Updated : 2 May, 2024

An interval is represented as a combination of start time and end time. Given a set of intervals, we need to write a program to check if any interval completely overlaps the other. 

Examples: 

Input: arr[] = {{1, 3}, {1, 7}, {4, 8}, {2, 5}}
Output: true
Explanation: The intervals {1, 3} completely overlaps in {1, 7}.

Input: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}
Output: false
Explanation: No pair of intervals overlap.

Naive Approach

A Simple Solution is to consider every pair of intervals and check if the pair overlaps or not.

Follow the given steps to solve the problem:

  • Iterate through each interval i, and for each interval i, loop through all the intervals j.
  • For two intervals i and j,
    • Check if the start time of interval i is less than or equal to the start time of interval j and the end time of interval i is greater than or equal to the end time of interval j.
    • Check if the start time of interval j is less than or equal to the start time of interval i and the end time of interval j is greater than or equal to the start time of interval i.
    • If any of above two condition is true, print indices of intervals i and j.
  • If no intervals completely overlap each other, print "No overlapping intervals found".

Below is the implementation of the approach:


Output
Yes
No

Time Complexity: O(n*n) as two nested for loops are executed. Here, n is size of the input array.
Auxiliary Space: O(1) as no extra space has been taken.

A better solution is to use Sorting. The idea is to sort all intervals in increasing order of start time and then in the sorted array, if the end time of an interval is not more than the end time of the previous interval, then there is a complete overlap.

Follow the given steps to solve the problem:

  • Sort the intervals in increasing order of start time.
  • Interate through each interval:
    • If the end time of an interval is not more than the end time of the previous interval, it means these two intervals overlap. Then Print the indices of the intervals.
  • If no intervals completely overlap each other, print "No overlapping intervals found".

Given below is an implementation of the above approach:  


Output
Yes
No

Time Complexity: O(n log n).
Auxiliary Space: O(1)

Comment
Article Tags: