Merge interval pattern: Find intersection of all intervals

Problem Statement:

You are given an array, you need to find the intersection of all the intervals.

Example:

 

Input: arr [] = [[1, 7], [2, 8], [3, 6]]

Output: [3, 6]

Explanation: [3,6] is the common interval that lies in all the given intervals.

Solution Explanation:

Take 2 pointers l and r.

Consider 2 intervals [l1, r1] and [l2, r2]

In thsi case there are 2 outcome possible:

Case 1: Intervals does not overlap.

In this case, r1 < l2 or r2 < l1. Return 0

Case 2: Intervals are overlapping

In this case the intersection will be max (l1, l2), min (r1, r2)

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void solution(vector<vector<int>>& arr)
{
    // First interval
    int l = arr[0][0];
    int r = arr[0][1];

    for (int i = 1; i < arr.size(); i++) {

        if (arr[i][0] > r || arr[i][1] < l) {
            cout << 0;
            return;
        }

        else {
            l = max(l, arr[i][0]);
            r = min(r, arr[i][1]);
        }
    }

    cout << "[" << l << ", " << r << "]";
}

int main()
{
    vector<vector<int>> arr = {{1, 7}, {2, 8}, {3, 6}};
    solution(arr);
}

Output

[3, 6]
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *