Given an integer R which signifies the range [0, R] and two arrays start[] and end[] of size N which signifies the starting and ending intervals in the range [0, R]. The task is to count the number of available non-overlapping intervals which need to be inserted in the arrays such that on merging the individual ranges in the arrays start[] and end[], the merged interval becomes [0, R].
Examples:Â Â
Input: R = 10, N = 3, start[] = {2, 5, 8}, end[] = {3, 9, 10}Â
Output: 2Â
Explanation:Â
The ranges {[2, 3], [5, 10]} are given by the array. In order to make the merged interval to [0, R], the ranges [0, 2] and [3, 5] should be inserted and merged. Therefore, two ranges needs to be inserted into the array.Input: R = 8, N = 2, start[] = {2, 6}, end[] = {3, 7}Â
Output: 3Â
Explanation:Â
The ranges {[2, 3], [6, 7]} are given by the array. In order to make the merged interval to [0, R], the ranges [0, 2], [3, 6] and [7, 8] should be inserted and merged. Therefore, three ranges needs to be inserted into the array. Â
Approach: The idea is to use sorting to solve the problem. Â
- Initially, both the given arrays are sorted so that used intervals come together.
- Now, the arrays are iterated in a sorted way (i.e.), one pointer would be pointing to start of start and another pointer would be pointing to start of end.
- If the current start element is smaller, this signifies that a new interval is being looked on and if the current end index is smaller, it signifies that the current interval is being exited.
- In this process, the count of current active intervals is stored. If at any point the current active count is 0, then there is an available interval. So, the count of the available interval is incremented.
- In this way, both the arrays are iterated.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation of the above approachÂ
#include <iostream>using namespace std;Â
// The following two functions// are used to sort the array.// QuickSort is being implemented in// the following functionsÂ
// Function to find the pivot indexint partition(int arr[], int l, int h){Â Â Â Â int pivot = arr[l];Â Â Â Â int i = l + 1;Â Â Â Â int j = h;Â
    while (i <= j) {Â
        while (i <= h               && arr[i] < pivot) {            i++;        }Â
        while (j > l               && arr[j] > pivot) {            j--;        }Â
        if (i < j) {Â
            int temp = arr[i];            arr[i] = arr[j];            arr[j] = temp;            i++;            j--;        }        else            i++;    }Â
    arr[l] = arr[j];    arr[j] = pivot;    return j;}Â
// Function to implement Quick Sortvoid sortArray(int arr[], int l, int h){Â Â Â Â if (l >= h)Â Â Â Â Â Â Â Â return;Â
    // Pivot is pointing to pivot index    // before which every element    // is smaller and after pivot,    // every element is greater    int pivot = partition(arr, l, h);Â
    // Sort the array before pivot element    sortArray(arr, l, pivot - 1);Â
    // Sort the array after pivot element    sortArray(arr, pivot + 1, h);}Â
// Function to count the available intervals// from the given range of numbersint findMaxIntervals(int start[], int end[],                     int n, int R){    int ans = 0;    int prev = 0;    int currActive = 0;    int i = 0;    int j = 0;Â
    // If range starts after 0    // then an interval is available    // from 0 to start[0]    if (start[0] > 0)        ans++;Â
    while (i < n && j < n) {        // When a new interval starts        if (start[i] < end[j]) {Â
            // Since index variable i is being            // incremented, the current active            // interval will also get incremented            i++;            currActive++;        }Â
        // When the current interval ends        else if (start[i] > end[j]) {Â
            // Since index variable j is being            // decremented, the currect active            // interval will also get decremented            j++;            currActive--;        }Â
        // When start and end both are same        // there is no change in currActive        else {            i++;            j++;        }        if (currActive == 0) {            ans++;        }    }Â
    // If the end of interval    // is before the range    // so interval is available    // at the end    if (end[n - 1] < R)        ans++;    return ans;}Â
// Driver codeint main(){Â Â Â Â int R, N;Â Â Â Â R = 10;Â Â Â Â N = 3;Â Â Â Â int start[N] = { 2, 5, 8 };Â Â Â Â int end[N] = { 3, 9, 10 };Â
    // Sort the start array    sortArray(start, 0, N - 1);Â
    // Sort the end array    sortArray(end, 0, N - 1);Â
    // Calling the function    cout << findMaxIntervals(        start, end, N, R);} |
Java
// Java implementation of the above approachimport java.util.*;class GFG{Â
// The following two functions// are used to sort the array.// QuickSort is being implemented in// the following functionsÂ
// Function to find the pivot indexstatic int partition(int arr[], int l, int h){Â Â Â Â int pivot = arr[l];Â Â Â Â int i = l + 1;Â Â Â Â int j = h;Â
    while (i <= j)     {        while (i <= h && arr[i] < pivot)         {            i++;        }Â
        while (j > l && arr[j] > pivot)         {            j--;        }Â
        if (i < j)         {            int temp = arr[i];            arr[i] = arr[j];            arr[j] = temp;            i++;            j--;        }        else            i++;    }Â
    arr[l] = arr[j];    arr[j] = pivot;    return j;}Â
// Function to implement Quick Sortstatic void sortArray(int arr[], int l, int h){Â Â Â Â if (l >= h)Â Â Â Â Â Â Â Â return;Â
    // Pivot is pointing to pivot index    // before which every element    // is smaller and after pivot,    // every element is greater    int pivot = partition(arr, l, h);Â
    // Sort the array before pivot element    sortArray(arr, l, pivot - 1);Â
    // Sort the array after pivot element    sortArray(arr, pivot + 1, h);}Â
// Function to count the available intervals// from the given range of numbersstatic int findMaxIntervals(int start[],                             int end[],                            int n, int R){    int ans = 0;    int prev = 0;    int currActive = 0;    int i = 0;    int j = 0;Â
    // If range starts after 0    // then an interval is available    // from 0 to start[0]    if (start[0] > 0)        ans++;Â
    while (i < n && j < n)     {        // When a new interval starts        if (start[i] < end[j])        {Â
            // Since index variable i is being            // incremented, the current active            // interval will also get incremented            i++;            currActive++;        }Â
        // When the current interval ends        else if (start[i] > end[j])         {Â
            // Since index variable j is being            // decremented, the currect active            // interval will also get decremented            j++;            currActive--;        }Â
        // When start and end both are same        // there is no change in currActive        else        {            i++;            j++;        }        if (currActive == 0)         {            ans++;        }    }Â
    // If the end of interval    // is before the range    // so interval is available    // at the end    if (end[n - 1] < R)        ans++;    return ans;}Â
// Driver codepublic static void main(String args[]){Â Â Â Â int R, N;Â Â Â Â R = 10;Â Â Â Â N = 3;Â Â Â Â int start[] = new int[]{ 2, 5, 8 };Â Â Â Â int end[] = new int[]{ 3, 9, 10 };Â
    // Sort the start array    sortArray(start, 0, N - 1);Â
    // Sort the end array    sortArray(end, 0, N - 1);Â
    // Calling the function    System.out.print(findMaxIntervals(start, end, N, R));}}Â
// This code is contributed by Code_Mech |
Python3
# Python3 implementation of the above approachÂ
# The following two functions# are used to sort the array.# QuickSort is being implemented in# the following functionsÂ
# Function to find the pivot indexdef partition(arr, l, h):Â Â Â Â Â Â Â Â Â pivot = arr[l]Â Â Â Â i = l + 1Â Â Â Â j = hÂ
    while (i <= j):        while (i <= h and arr[i] < pivot):            i += 1Â
        while (j > l and arr[j] > pivot):            j -= 1Â
        if (i < j):            temp = arr[i]            arr[i] = arr[j]            arr[j] = temp            i += 1            j -= 1        else:            i += 1Â
    arr[l] = arr[j]    arr[j] = pivot    return jÂ
# Function to implement Quick Sortdef sortArray(arr, l, h):Â Â Â Â Â Â Â Â Â if (l >= h):Â Â Â Â Â Â Â Â returnÂ
    # Pivot is pointing to pivot index    # before which every element    # is smaller and after pivot,    # every element is greater    pivot = partition(arr, l, h)Â
    # Sort the array before pivot element    sortArray(arr, l, pivot - 1)Â
    # Sort the array after pivot element    sortArray(arr, pivot + 1, h)Â
# Function to count the available intervals# from the given range of numbersdef findMaxIntervals(start, end, n, R):Â Â Â Â Â Â Â Â Â ans = 0Â Â Â Â prev = 0Â Â Â Â currActive = 0Â Â Â Â i = 0Â Â Â Â j = 0Â
    # If range starts after 0    # then an interval is available    # from 0 to start[0]    if (start[0] > 0):        ans += 1Â
    while (i < n and j < n):                 # When a new interval starts        if (start[i] < end[j]):                         # Since index variable i is being            # incremented, the current active            # interval will also get incremented            i += 1            currActive += 1Â
        # When the current interval ends        elif (start[i] > end[j]):                         # Since index variable j is being            # decremented, the currect active            # interval will also get decremented            j += 1            currActive -= 1Â
        # When start and end both are same        # there is no change in currActive        else:            i += 1            j += 1        if (currActive == 0):            ans += 1Â
    # If the end of interval    # is before the range    # so interval is available    # at the end    if (end[n - 1] < R):        ans += 1    return ansÂ
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â R = 10Â Â Â Â N = 3Â Â Â Â start = [ 2, 5, 8 ]Â Â Â Â end = [ 3, 9, 10 ]Â
    # Sort the start array    sortArray(start, 0, N - 1)Â
    # Sort the end array    sortArray(end, 0, N - 1)Â
    # Calling the function    print(findMaxIntervals(start, end, N, R))Â
# This code is contributed by Surendra_Gangwar |
C#
// C# implementation of the above approachusing System;class GFG{Â
// The following two functions// are used to sort the array.// QuickSort is being implemented in// the following functionsÂ
// Function to find the pivot indexstatic int partition(int []arr, int l, int h){Â Â Â Â int pivot = arr[l];Â Â Â Â int i = l + 1;Â Â Â Â int j = h;Â
    while (i <= j)     {        while (i <= h && arr[i] < pivot)         {            i++;        }Â
        while (j > l && arr[j] > pivot)         {            j--;        }Â
        if (i < j)         {            int temp = arr[i];            arr[i] = arr[j];            arr[j] = temp;            i++;            j--;        }        else            i++;    }Â
    arr[l] = arr[j];    arr[j] = pivot;    return j;}Â
// Function to implement Quick Sortstatic void sortArray(int []arr, int l, int h){Â Â Â Â if (l >= h)Â Â Â Â Â Â Â Â return;Â
    // Pivot is pointing to pivot index    // before which every element    // is smaller and after pivot,    // every element is greater    int pivot = partition(arr, l, h);Â
    // Sort the array before pivot element    sortArray(arr, l, pivot - 1);Â
    // Sort the array after pivot element    sortArray(arr, pivot + 1, h);}Â
// Function to count the available intervals// from the given range of numbersstatic int findMaxIntervals(int []start,                             int []end,                            int n, int R){    int ans = 0;    int prev = 0;    int currActive = 0;    int i = 0;    int j = 0;Â
    // If range starts after 0    // then an interval is available    // from 0 to start[0]    if (start[0] > 0)        ans++;Â
    while (i < n && j < n)     {        // When a new interval starts        if (start[i] < end[j])        {Â
            // Since index variable i is being            // incremented, the current active            // interval will also get incremented            i++;            currActive++;        }Â
        // When the current interval ends        else if (start[i] > end[j])         {Â
            // Since index variable j is being            // decremented, the currect active            // interval will also get decremented            j++;            currActive--;        }Â
        // When start and end both are same        // there is no change in currActive        else        {            i++;            j++;        }        if (currActive == 0)         {            ans++;        }    }Â
    // If the end of interval    // is before the range    // so interval is available    // at the end    if (end[n - 1] < R)        ans++;    return ans;}Â
// Driver codepublic static void Main(){Â Â Â Â int R, N;Â Â Â Â R = 10;Â Â Â Â N = 3;Â Â Â Â int []start = new int[]{ 2, 5, 8 };Â Â Â Â int []end = new int[]{ 3, 9, 10 };Â
    // Sort the start array    sortArray(start, 0, N - 1);Â
    // Sort the end array    sortArray(end, 0, N - 1);Â
    // Calling the function    Console.Write(findMaxIntervals(start, end, N, R));}}Â
// This code is contributed by Code_Mech |
Javascript
<script>Â
// Javascript implementation of the above approachÂ
// The following two functions// are used to sort the array.// QuickSort is being implemented in// the following functions   // Function to find the pivot indexfunction partition(arr, l, h){    let pivot = arr[l];    let i = l + 1;    let j = h;       while (i <= j)     {        while (i <= h && arr[i] < pivot)         {            i++;        }           while (j > l && arr[j] > pivot)         {            j--;        }           if (i < j)         {            let temp = arr[i];            arr[i] = arr[j];            arr[j] = temp;            i++;            j--;        }        else            i++;    }       arr[l] = arr[j];    arr[j] = pivot;    return j;}   // Function to implement Quick Sortfunction sortArray(arr, l, h){    if (l >= h)        return;       // Pivot is pointing to pivot index    // before which every element    // is smaller and after pivot,    // every element is greater    let pivot = partition(arr, l, h);       // Sort the array before pivot element    sortArray(arr, l, pivot - 1);       // Sort the array after pivot element    sortArray(arr, pivot + 1, h);}   // Function to count the available intervals// from the given range of numbersfunction findMaxIntervals(start,                             end, n, R){    let ans = 0;    let prev = 0;    let currActive = 0;    let i = 0;    let j = 0;       // If range starts after 0    // then an interval is available    // from 0 to start[0]    if (start[0] > 0)        ans++;       while (i < n && j < n)     {        // When a new interval starts        if (start[i] < end[j])        {               // Since index variable i is being            // incremented, the current active            // interval will also get incremented            i++;            currActive++;        }           // When the current interval ends        else if (start[i] > end[j])         {               // Since index variable j is being            // decremented, the currect active            // interval will also get decremented            j++;            currActive--;        }           // When start and end both are same        // there is no change in currActive        else        {            i++;            j++;        }        if (currActive == 0)         {            ans++;        }    }       // If the end of interval    // is before the range    // so interval is available    // at the end    if (end[n - 1] < R)        ans++;    return ans;}     Â
// Driver Code         let R, N;    R = 10;    N = 3;    let start = [ 2, 5, 8 ];    let end = [ 3, 9, 10 ];       // Sort the start array    sortArray(start, 0, N - 1);       // Sort the end array    sortArray(end, 0, N - 1);       // Calling the function       document.write(findMaxIntervals(start, end, N, R));     </script> |
2
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
