Check if any two intervals intersect in a given set
Last Updated :
26 Mar, 2025
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.
[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.
C++
#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;
}
Java
// 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");
}
}
Python
# 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")
C#
// 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");
}
}
JavaScript
// 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");
[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".
C++
#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;
}
Java
// 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");
}
}
Python
# 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")
C#
// 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");
}
}
JavaScript
// 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");
[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:
C++
#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;
}
Java
// 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");
}
}
Python
# 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")
C#
// 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");
}
}
JavaScript
// 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");
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)
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read