Open In App

Intersection of intervals given by two lists

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists.
Note: Disjoint means no element is common in a list

Examples: 

Input arr1[][] = {{0, 4}, {5, 10}, {13, 20}, {24, 25}}  arr2[][] = {{1, 5}, {8, 12}, {15, 24}, {25, 26}} 
Output {{1, 4}, {5, 5}, {8, 10}, {15, 20}, {24, 24}, {25, 25}}
Explanation {1, 4} is the overlap of {0, 4} and {1, 5}. Similarly, {24, 24} is the overlap of {24, 25} and {15, 24}.

Input arr1[][] = {{0, 2}, {5, 10}, {12, 22}, {24, 25}}  arr2[][] = {{1, 4}, {9, 12}, {15, 24}, {25, 26}} 
Output {{1, 2}, {9, 10}, {12, 12}, {15, 22}, {24, 24}, {25, 25}} 
Explanation {1, 2} is the overlap of {0, 2} and {1, 4}. Similarly, {12, 12} is the overlap of {12, 22} and {9, 12}. 

We use two-pointer to solve by following these steps:

Use two pointers, i and j, to traverse arr1 and arr2. For each pair, find the overlap:

l = max⁡(arr1[i][0],arr2[j][0]),
r = min⁡(arr1[i][1],arr2[j][1])

If l ≤ r, add [l, r] to the result. Move the pointer with the smaller endpoint to continue.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print intersecting intervals
void printIntervals(vector<vector<int>> arr1, vector<vector<int>> arr2)
{

    // i and j pointers for
    // arr1 and arr2 respectively
    int i = 0, j = 0;

    // Size of the two lists
    int n = arr1.size(), m = arr2.size();

    // Loop through all intervals unless
    // one of the interval gets exhausted
    while (i < n && j < m)
    {
        // Left bound for intersecting segment
        int l = max(arr1[i][0], arr2[j][0]);

        // Right bound for intersecting segment
        int r = min(arr1[i][1], arr2[j][1]);

        // If segment is valid print it
        if (l <= r)
            cout << "[" << l << ", " << r << "]\n";

        // If i-th interval's right
        // bound is smaller
        // increment i else
        // increment j
        if (arr1[i][1] < arr2[j][1])
            i++;
        else
            j++;
    }
}

int main()
{

    vector<vector<int>> arr1 = {{0, 4}, {5, 10}, {13, 20}, {24, 25}};

    vector<vector<int>> arr2 = {{1, 5}, {8, 12}, {15, 24}, {25, 26}};

    printIntervals(arr1, arr2);

    return 0;
}
Java
// Java implementation to find 
// intersecting intervals
class GFG{

// Function to print intersecting intervals
static void printIntervals(int arr1[][],
                           int arr2[][])
{
    
    // i and j pointers for arr1 and 
    // arr2 respectively
    int i = 0, j = 0;
    
    int n = arr1.length, m = arr2.length;
    
    // Loop through all intervals unless  
    // one of the interval gets exhausted
    while (i < n && j < m) 
    {
        
        // Left bound for intersecting segment
        int l = Math.max(arr1[i][0], arr2[j][0]);

        // Right bound for intersecting segment
        int r = Math.min(arr1[i][1], arr2[j][1]);
        
        // If segment is valid print it
        if (l <= r) 
            System.out.println("[" + l + ", " +
                                 r + "]");

        // If i-th interval's right bound is 
        // smaller increment i else increment j
        if (arr1[i][1] < arr2[j][1])
            i++;
        else
            j++;
    }
}

public static void main(String[] args)
{
    int arr1[][] = { { 0, 4 }, { 5, 10 },
                     { 13, 20 }, { 24, 25 } };

    int arr2[][] = { { 1, 5 }, { 8, 12 }, 
                     { 15, 24 }, { 25, 26 } };

    printIntervals(arr1, arr2);
}
}
Python
# Python3 implementation to find 
# intersecting intervals

# Function to print intersecting 
# intervals
def printIntervals(arr1, arr2):
    
    # i and j pointers for arr1 
    # and arr2 respectively
    i = j = 0
    
    n = len(arr1)
    m = len(arr2)

    # Loop through all intervals unless one 
    # of the interval gets exhausted
    while i < n and j < m:
        
        # Left bound for intersecting segment
        l = max(arr1[i][0], arr2[j][0])
        
        # Right bound for intersecting segment
        r = min(arr1[i][1], arr2[j][1])
        
        # If segment is valid print it
        if l <= r: 
            print('[', l, ',', r, ']')

        # If i-th interval's right bound is 
        # smaller increment i else increment j
        if arr1[i][1] < arr2[j][1]:
            i += 1
        else:
            j += 1

# Driver code
arr1 = [ [ 0, 4 ], [ 5, 10 ],
         [ 13, 20 ], [ 24, 25 ] ]

arr2 = [ [ 1, 5 ], [ 8, 12 ], 
         [ 15, 24 ], [ 25, 26 ] ]

printIntervals(arr1, arr2)
C#
// C# implementation to find 
// intersecting intervals
using System;
class GFG{
    
// Function to print intersecting intervals
static void printIntervals(int [,]arr1,
                           int [,]arr2)
{
    
    // i and j pointers for arr1 and 
    // arr2 respectively
    int i = 0, j = 0;
    
    int n = arr1.GetLength(0),
        m = arr2.GetLength(0);
    
    // Loop through all intervals unless 
    // one of the interval gets exhausted
    while (i < n && j < m) 
    {
    
        // Left bound for intersecting segment
        int l = Math.Max(arr1[i, 0], arr2[j, 0]);
       
        // Right bound for intersecting segment
        int r = Math.Min(arr1[i, 1], arr2[j, 1]);
    
        // If segment is valid print it
        if (l <= r) 
        Console.WriteLine("[" + l + ", " +
                            r + "]");
                            
        // If i-th interval's right bound is 
        // smaller increment i else increment j
        if (arr1[i, 1] < arr2[j, 1])
            i++;
        else
            j++;
    }
}

public static void Main(String[] args)
{
    int [,]arr1 = { { 0, 4 }, { 5, 10 },
                    { 13, 20 }, { 24, 25 } };
                    
    int [,]arr2 = { { 1, 5 }, { 8, 12 }, 
                    { 15, 24 }, { 25, 26 } };
                    
    printIntervals(arr1, arr2);
}
}
JavaScript
function printIntervals(arr1, arr2)
{

    // i and j pointers for arr1 and
    // arr2 respectively
    var i = 0, j = 0;

    var n = arr1.length, m = arr2.length;

    // Loop through all intervals unless
    // one of the interval gets exhausted
    while (i < n && j < m) {

        // Left bound for intersecting segment
        var l = Math.max(arr1[i][0], arr2[j][0]);

        // Right bound for intersecting segment
        var r = Math.min(arr1[i][1], arr2[j][1]);

        // If segment is valid print it
        if (l <= r)
            console.log("[" + l + ", " + r + "]");

        // If i-th interval's right bound is
        // smaller increment i else increment j
        if (arr1[i][1] < arr2[j][1])
            i++;
        else
            j++;
    }
}

var arr1 = [ [ 0, 4 ], [ 5, 10 ], [ 13, 20 ], [ 24, 25 ] ];

var arr2 = [ [ 1, 5 ], [ 8, 12 ], [ 15, 24 ], [ 25, 26 ] ];

printIntervals(arr1, arr2);

Output
[1, 4]
[5, 5]
[8, 10]
[15, 20]
[24, 24]
[25, 25]

Time Complexity O(n + m)
Auxiliary Space O(1)


Next Article

Similar Reads