An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect.
Examples:
Input: arr[] = [[1, 3], [5, 7], [2, 4], [6, 8]]
Output: True
Explanation: The intervals {1, 3} and {2, 4} overlap
Input: arr[] = [[1, 3], [7, 9], [4, 6], [10, 13]]
Output: False
Explanation: No pair of intervals overlap.
Table of Content
[Naive Approach] - Using Nested Loops - O(n ^ 2) Time and O(1) Space
The idea is to consider every pair of intervals and check if the pair intersects or not. To do so, run a nested loops, where the outer loop marks the current interval and for each iteration of outer loops, the inner loop traverse through each interval and checks if any of the interval intersects.
#include <bits/stdc++.h>
using namespace std;
// Function to check if any two intervals
// intersect with each other
bool isIntersecting(vector<int> a, vector<int> b) {
if (a[1] < b[0] || b[1] < a[0])
return false;
return true;
}
// Function to check if any two intervals
// in the given list intersect with each other
bool isIntersect(vector<vector<int>> intervals) {
int n = intervals.size();
// Iterate over all pairs of intervals
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// check, if two intervals intersect
if (isIntersecting(intervals[i], intervals[j]))
return true;
}
}
return false;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
cout << "True";
else
cout << "False";
return 0;
}
// Function to check if any two intervals
// intersect with each other
import java.util.*;
class GfG {
// Function to check if any two intervals
// intersect with each other
static boolean isIntersecting(int[] a, int[] b) {
if (a[1] < b[0] || b[1] < a[0])
return false;
return true;
}
// Function to check if any two intervals
// in the given list intersect with each other
static boolean isIntersect(int[][] intervals) {
int n = intervals.length;
// Iterate over all pairs of intervals
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// check, if two intervals intersect
if (isIntersecting(intervals[i], intervals[j]))
return true;
}
}
return false;
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
System.out.println("True");
else
System.out.println("False");
}
}
# Function to check if any two intervals
# intersect with each other
def isIntersecting(a, b):
if a[1] < b[0] or b[1] < a[0]:
return False
return True
# Function to check if any two intervals
# in the given list intersect with each other
def isIntersect(intervals):
n = len(intervals)
# Iterate over all pairs of intervals
for i in range(n):
for j in range(i+1, n):
# check, if two intervals intersect
if isIntersecting(intervals[i], intervals[j]):
return True
return False
if __name__ == "__main__":
intervals = [[1, 3], [5, 7], [2, 4], [6, 8]]
if isIntersect(intervals):
print("True")
else:
print("False")
// Function to check if any two intervals
// intersect with each other
using System;
class GfG {
// Function to check if any two intervals
// intersect with each other
static bool isIntersecting(int[] a, int[] b) {
if (a[1] < b[0] || b[1] < a[0])
return false;
return true;
}
// Function to check if any two intervals
// in the given array intersect with each other
static bool isIntersect(int[][] intervals) {
int n = intervals.Length;
// Iterate over all pairs of intervals
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// check, if two intervals intersect
if (isIntersecting(intervals[i], intervals[j]))
return true;
}
}
return false;
}
static void Main() {
int[][] intervals = new int[][] {
new int[] {1, 3},
new int[] {5, 7},
new int[] {2, 4},
new int[] {6, 8}
};
if (isIntersect(intervals))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
// Function to check if any two intervals
// intersect with each other.
function isIntersecting(a, b) {
if (a[1] < b[0] || b[1] < a[0])
return false;
return true;
}
// Function to check if any two intervals
// in the given list intersect with each other
function isIntersect(intervals) {
let n = intervals.length;
// Iterate over all pairs of intervals
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// check, if two intervals intersect
if (isIntersecting(intervals[i], intervals[j]))
return true;
}
}
return false;
}
let intervals = [[1, 3], [5, 7], [2, 4], [6, 8]];
if (isIntersect(intervals))
console.log("True");
else
console.log("False");
Output
True
[Expected Approach] - Using Sorting - O(n * log n) Time and O(1) Space
The idea is to sort the given list of intervals in the increasing order of start time. For each interval, check if the start time of current interval is less than or equal to the end time of previous interval, if so, return "True". If no such interval is found, return "False".
#include <bits/stdc++.h>
using namespace std;
// Function to check if any two intervals
// in the given list intersect with each other
bool isIntersect(vector<vector<int>> intervals) {
int n = intervals.size();
// sort the intervals based on the starting time
sort(intervals.begin(), intervals.end());
// check if any of the interval
// intersects with its previous
for (int i = 1; i < n; i++) {
if (intervals[i][0] <= intervals[i - 1][1])
return true;
}
return false;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
cout << "True";
else
cout << "False";
return 0;
}
// Function to check if any two intervals
// in the given list intersect with each other
import java.util.*;
class GfG {
// Function to check if any two intervals
// in the given list intersect with each other
static boolean isIntersect(int[][] intervals) {
int n = intervals.length;
// sort the intervals based on the starting time
Arrays.sort(intervals, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return Integer.compare(a[0], b[0]);
}
});
// check if any of the interval
// intersects with its previous
for (int i = 1; i < n; i++) {
if (intervals[i][0] <= intervals[i - 1][1])
return true;
}
return false;
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
System.out.println("True");
else
System.out.println("False");
}
}
# Function to check if any two intervals
# in the given list intersect with each other
def isIntersect(intervals):
n = len(intervals)
# sort the intervals based on the starting time
intervals.sort(key=lambda x: x[0])
# check if any of the interval
# intersects with its previous
for i in range(1, n):
if intervals[i][0] <= intervals[i - 1][1]:
return True
return False
if __name__ == "__main__":
intervals = [[1, 3], [5, 7], [2, 4], [6, 8]]
if isIntersect(intervals):
print("True")
else:
print("False")
// Function to check if any two intervals
// in the given list intersect with each other
using System;
using System.Linq;
class GfG {
// Function to check if any two intervals
// in the given list intersect with each other
static bool IsIntersect(int[][] intervals) {
int n = intervals.Length;
// sort the intervals based on the starting time
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
// check if any of the interval
// intersects with its previous
for (int i = 1; i < n; i++) {
if (intervals[i][0] <= intervals[i - 1][1])
return true;
}
return false;
}
public static void Main(string[] args) {
int[][] intervals = new int[][] { new int[] { 1, 3 },
new int[] { 5, 7 }, new int[] { 2, 4 },
new int[] { 6, 8 } };
if (IsIntersect(intervals))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
// Function to check if any two intervals
// in the given list intersect with each other.
function isIntersect(intervals) {
let n = intervals.length;
// sort the intervals based on the starting time
intervals.sort((a, b) => a[0] - b[0]);
// check if any of the interval
// intersects with its previous
for (let i = 1; i < n; i++) {
if (intervals[i][0] <= intervals[i - 1][1])
return true;
}
return false;
}
let intervals = [[1, 3], [5, 7], [2, 4], [6, 8]];
if (isIntersect(intervals))
console.log("True");
else
console.log("False");
Output
True
[Alternate Approach] - Using Prefix Sum
The idea is to map all the start and end time of all the intervals in an array, where start increments the corresponding index and end time decrements it. Thereafter, find the prefix sum of this array. If at any index, the value is greater than 1, then there exists a intersecting interval, thus return "True", otherwise return "False".
Follow the below given steps:
- Find the overall maximum end time. Let it be max_ele
- Initialize an array of size max_ele with 0.
- For every interval [start, end], increment the value at index start, i.e. arr[start]++ and decrement the value at index (end + 1), i.e. arr[end + 1]- -.
- Compute the prefix sum of this array (arr[]).
- Every index, i of this prefix sum array will tell how many times i has occurred in all the intervals taken together. If this value is greater than 1, then it occurs in 2 or more intervals.
- So, simply initialize the result variable as false and while traversing the prefix sum array, change the result variable to true whenever the value at that index is greater than 1.
Below is given the implementation:
#include <bits/stdc++.h>
using namespace std;
// Function to check if any two intervals
// in the given list intersect with each other
bool isIntersect(vector<vector<int>> intervals) {
int n = intervals.size();
// find the maximum end time
int max_end = 0;
for (int i = 0; i < n; i++) {
max_end = max(max_end, intervals[i][1]);
}
// create an array of size max_end
// and initialize it with 0
vector<int> arr(max_end + 2, 0);
// iterate over all intervals
for (int i = 0; i < n; i++) {
int start = intervals[i][0];
int end = intervals[i][1];
// increment the start time
arr[start] += 1;
// decrement the end time
arr[end + 1] -= 1;
}
// iterate over the array and
// calculate the prefix sum
for (int i = 1; i <= max_end; i++) {
arr[i] += arr[i - 1];
// if the prefix sum is greater than 1
// then the intervals intersect
if (arr[i] > 1)
return true;
}
return false;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
cout << "True";
else
cout << "False";
return 0;
}
// Function to check if any two intervals
// in the given list intersect with each other
import java.util.*;
class GfG {
// Function to check if any two intervals
// in the given list intersect with each other
static boolean isIntersect(int[][] intervals) {
int n = intervals.length;
// find the maximum end time
int maxEnd = 0;
for (int i = 0; i < n; i++) {
maxEnd = Math.max(maxEnd, intervals[i][1]);
}
// create an array of size maxEnd
// and initialize it with 0
int[] arr = new int[maxEnd + 2];
// iterate over all intervals
for (int i = 0; i < n; i++) {
int start = intervals[i][0];
int end = intervals[i][1];
// increment the start time
arr[start] += 1;
// decrement the end time
arr[end + 1] -= 1;
}
// iterate over the array and
// calculate the prefix sum
for (int i = 1; i <= maxEnd; i++) {
arr[i] += arr[i - 1];
// if the prefix sum is greater than 1
// then the intervals intersect
if (arr[i] > 1)
return true;
}
return false;
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {5, 7}, {2, 4}, {6, 8}};
if (isIntersect(intervals))
System.out.println("True");
else
System.out.println("False");
}
}
# Function to check if any two intervals
# in the given list intersect with each other.
def isIntersect(intervals):
n = len(intervals)
# find the maximum end time
max_end = 0
for i in range(n):
max_end = max(max_end, intervals[i][1])
# create an array of size max_end
# and initialize it with 0
arr = [0] * (max_end + 2)
# iterate over all intervals
for i in range(n):
start = intervals[i][0]
end = intervals[i][1]
# increment the start time
arr[start] += 1
# decrement the end time
arr[end + 1] -= 1
# iterate over the array and
# calculate the prefix sum
for i in range(1, max_end + 1):
arr[i] += arr[i - 1]
# if the prefix sum is greater than 1
# then the intervals intersect
if arr[i] > 1:
return True
return False
if __name__ == "__main__":
intervals = [[1, 3], [5, 7], [2, 4], [6, 8]]
if isIntersect(intervals):
print("True")
else:
print("False")
// Function to check if any two intervals
// in the given list intersect with each other
using System;
using System.Collections.Generic;
class GfG {
// Function to check if any two intervals
// in the given list intersect with each other
static bool isIntersect(List<List<int>> intervals) {
int n = intervals.Count;
// find the maximum end time
int max_end = 0;
for (int i = 0; i < n; i++) {
max_end = Math.Max(max_end, intervals[i][1]);
}
// create an array of size max_end
// and initialize it with 0
int[] arr = new int[max_end + 2];
for (int i = 0; i < arr.Length; i++) {
arr[i] = 0;
}
// iterate over all intervals
for (int i = 0; i < n; i++) {
int start = intervals[i][0];
int end = intervals[i][1];
// increment the start time
arr[start] += 1;
// decrement the end time
arr[end + 1] -= 1;
}
// iterate over the array and
// calculate the prefix sum
for (int i = 1; i <= max_end; i++) {
arr[i] += arr[i - 1];
// if the prefix sum is greater than 1
// then the intervals intersect
if (arr[i] > 1)
return true;
}
return false;
}
static void Main() {
List<List<int>> intervals = new List<List<int>> {
new List<int> {1, 3},
new List<int> {5, 7},
new List<int> {2, 4},
new List<int> {6, 8}
};
if (isIntersect(intervals))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
// Function to check if any two intervals
// in the given list intersect with each other.
function isIntersect(intervals) {
let n = intervals.length;
// find the maximum end time
let max_end = 0;
for (let i = 0; i < n; i++) {
max_end = Math.max(max_end, intervals[i][1]);
}
// create an array of size max_end
// and initialize it with 0
let arr = new Array(max_end + 2).fill(0);
// iterate over all intervals
for (let i = 0; i < n; i++) {
let start = intervals[i][0];
let end = intervals[i][1];
// increment the start time
arr[start] += 1;
// decrement the end time
arr[end + 1] -= 1;
}
// iterate over the array and
// calculate the prefix sum
for (let i = 1; i <= max_end; i++) {
arr[i] += arr[i - 1];
// if the prefix sum is greater than 1
// then the intervals intersect
if (arr[i] > 1)
return true;
}
return false;
}
let intervals = [[1, 3], [5, 7], [2, 4], [6, 8]];
if (isIntersect(intervals))
console.log("True");
else
console.log("False");
Output
True
Time Complexity : O(m + n), where m is the maximum end time in the given list of intervals and n is number of intervals..
Space Complexity: O(m)