Skip to content
Related Articles

Related Articles

Improve Article
Find Intersection of all Intervals
  • Difficulty Level : Medium
  • Last Updated : 11 May, 2021

Given N intervals of the form of [l, r], the task is to find the intersection of all the intervals. An intersection is an interval that lies within all of the given intervals. If no such intersection exists then print -1.
Examples: 
 

Input: arr[] = {{1, 6}, {2, 8}, {3, 10}, {5, 8}} 
Output: [5, 6] 
[5, 6] is the common interval that lies in all the given intervals.
Input: arr[] = {{1, 6}, {8, 18}} 
Output: -1 
No intersection exists between the two given ranges. 
 

 

Approach: 
 

  • Start by considering first interval as the required answer.
  • Now, starting from the second interval, try searching for the intersection. Two cases can arise: 
    1. There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists.
    2. There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)].

Below is the implementation of the above approach:
 



C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the intersection
void findIntersection(int intervals[][2], int N)
{
    // First interval
    int l = intervals[0][0];
    int r = intervals[0][1];
 
    // Check rest of the intervals and find the intersection
    for (int i = 1; i < N; i++) {
 
        // If no intersection exists
        if (intervals[i][0] > r || intervals[i][1] < l) {
            cout << -1;
            return;
        }
 
        // Else update the intersection
        else {
            l = max(l, intervals[i][0]);
            r = min(r, intervals[i][1]);
        }
    }
 
    cout << "[" << l << ", " << r << "]";
}
 
// Driver code
int main()
{
    int intervals[][2] = {
        { 1, 6 },
        { 2, 8 },
        { 3, 10 },
        { 5, 8 }
    };
    int N = sizeof(intervals) / sizeof(intervals[0]);
    findIntersection(intervals, N);
}

Java




// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
// Function to print the intersection
static void findIntersection(int intervals[][], int N)
{
    // First interval
    int l = intervals[0][0];
    int r = intervals[0][1];
 
    // Check rest of the intervals
    // and find the intersection
    for (int i = 1; i < N; i++)
    {
 
        // If no intersection exists
        if (intervals[i][0] > r ||
            intervals[i][1] < l)
        {
            System.out.println(-1);
            return;
        }
 
        // Else update the intersection
        else
        {
            l = Math.max(l, intervals[i][0]);
            r = Math.min(r, intervals[i][1]);
        }
    }
    System.out.println ("[" + l +", " + r + "]");
}
 
    // Driver code
    public static void main (String[] args)
    {
 
        int intervals[][] = {{ 1, 6 },
                            { 2, 8 },
                            { 3, 10 },
                            { 5, 8 }};
        int N = intervals.length;
        findIntersection(intervals, N);
    }
}
 
// This Code is contributed by ajit..

Python




# Python3 implementation of the approach
 
# Function to print the intersection
def findIntersection(intervals,N):
 
    # First interval
    l = intervals[0][0]
    r = intervals[0][1]
 
    # Check rest of the intervals
    # and find the intersection
    for i in range(1,N):
 
        # If no intersection exists
        if (intervals[i][0] > r or intervals[i][1] < l):
            print(-1)
 
        # Else update the intersection
        else:
            l = max(l, intervals[i][0])
            r = min(r, intervals[i][1])
         
     
 
    print("[",l,", ",r,"]")
 
# Driver code
 
intervals= [
            [ 1, 6 ],
            [ 2, 8 ],
            [ 3, 10 ],
            [ 5, 8 ]
            ]
N =len(intervals)
findIntersection(intervals, N)
 
# this code is contributed by mohit kumar

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to print the intersection
static void findIntersection(int [,]intervals, int N)
{
    // First interval
    int l = intervals[0, 0];
    int r = intervals[0, 1];
 
    // Check rest of the intervals
    // and find the intersection
    for (int i = 1; i < N; i++)
    {
 
        // If no intersection exists
        if (intervals[i, 0] > r ||
            intervals[i, 1] < l)
        {
            Console.WriteLine(-1);
            return;
        }
 
        // Else update the intersection
        else
        {
            l = Math.Max(l, intervals[i, 0]);
            r = Math.Min(r, intervals[i, 1]);
        }
    }
    Console.WriteLine("[" + l + ", " + r + "]");
}
 
// Driver code
public static void Main()
{
    int [,]intervals = {{ 1, 6 }, { 2, 8 },
                        { 3, 10 }, { 5, 8 }};
    int N = intervals.GetLength(0);
    findIntersection(intervals, N);
}
}
 
// This code is contributed by Ryuga

PHP




<?php
// PHP implementation of the approach
 
// Function to print the intersection
function findIntersection($intervals, $N)
{
    // First interval
    $l = $intervals[0][0];
    $r = $intervals[0][1];
 
    // Check rest of the intervals and
    // find the intersection
    for ($i = 1; $i < $N; $i++)
    {
 
        // If no intersection exists
        if ($intervals[$i][0] > $r ||
            $intervals[$i][1] < $l)
        {
            echo -1;
            return;
        }
 
        // Else update the intersection
        else
        {
            $l = max($l, $intervals[$i][0]);
            $r = min($r, $intervals[$i][1]);
        }
    }
 
    echo "[" . $l . ", " . $r . "]";
}
 
// Driver code
$intervals = array(array(1, 6), array(2, 8),
                   array(3, 10), array(5, 8));
$N = sizeof($intervals);
findIntersection($intervals, $N);
 
// This code is contributed
// by Akanksha Rai
?>

Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to print the intersection
    function findIntersection(intervals, N)
    {
        // First interval
        let l = intervals[0][0];
        let r = intervals[0][1];
 
        // Check rest of the intervals
        // and find the intersection
        for (let i = 1; i < N; i++)
        {
 
            // If no intersection exists
            if (intervals[i][0] > r ||
                intervals[i][1] < l)
            {
                document.write(-1 + "</br>");
                return;
            }
 
            // Else update the intersection
            else
            {
                l = Math.max(l, intervals[i][0]);
                r = Math.min(r, intervals[i][1]);
            }
        }
        document.write("[" + l +", " + r + "]" + "</br>");
    }
     
    let intervals = [[ 1, 6 ],
                     [ 2, 8 ],
                     [ 3, 10],
                     [ 5, 8 ]];
    let N = intervals.length;
    findIntersection(intervals, N);
 
</script>
Output: 
[5, 6]

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live




My Personal Notes arrow_drop_up
Recommended Articles
Page :