Given an array arr[] consisting of N pairs and a positive integer K, the task is to select the minimum number of pairs such that it covers the entire range [0, K]. If it is not possible to cover the range [0, K], then print -1.
Examples :
Input: arr[] = {{0, 3}, {2, 5}, {5, 6}, {6, 8}, {6, 10}}, K = 10
Output: 4
Explanation: One of the optimal ways is to select the ranges {{0, 3}, {2, 5}, {5, 6}, {6, 10}} which covers the entire range [0, 10].Input: arr[] = {{0, 4}, {1, 5}, {5, 6}, {8, 10}}, N = 10
Output : -1
Naive Approach: The simplest approach to solve the problem is to generate all possible subsets and check for each subset, if it covers the entire range or not.Â
Time Complexity: O(2N × N)Â
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by sorting the array in increasing order on the basis of the left element and for pairs with equal left elements, sort the elements in decreasing order of their right element. Now, choose the pairs optimally.Â
Follow the steps below to solve the problem:
- Sort the vector of pairs arr[] in increasing order of left element and if left elements are equal, then sort the array in decreasing order of right element of pair.
- Check if arr[0][0] != 0 then print -1.
- Initialize a variable, say R as arr[0][1] which stores the right bound of the range and ans as 1 which stores number of ranges needed to cover the range [0, Â K].
- Iterate in the range [0, N-1] using the variable i and perform the following steps:
- If R == K, terminate the loop.
- Initialize a variable, say maxr as R which stores the maximum right bound where left bound ? R.
- Iterate in the range [i+1, N-1] using the variable j and perform the following steps:
- If arr[j][0] ? R, then modify the value of maxr as max(maxr, arr[j][1]).
- Modify the value of i as j-1 and the value of R as maxr and increment the value of ans by 1.
- If R is not equal to K, then print -1.
- Otherwise, print the value of ans.
Below is the implementation of the above approach:
C++14
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to sort the elements in// increasing order of left element and// sort pairs with equal left element in// decreasing order of right elementstatic bool cmp(pair<int, int> a, pair<int, int> b){Â Â Â Â if (a.first == b.first) {Â Â Â Â Â Â Â Â return a.second > b.second;Â Â Â Â }Â Â Â Â else {Â Â Â Â Â Â Â Â return b.first > a.first;Â Â Â Â }}Â
// Function to select minimum number of pairs// such that it covers the entire range [0, K]int MinimumPairs(vector<pair<int, int> > arr, int K){Â Â Â Â int N = arr.size();Â
    // Sort the array using comparator    sort(arr.begin(), arr.end(), cmp);Â
    // If the start element    // is not equal to 0    if (arr[0].first != 0) {        return -1;    }Â
    // Stores the minimum    // number of pairs required    int ans = 1;Â
    // Stores the right bound of the range    int R = arr[0].second;Â
    // Iterate in the range[0, N-1]    for (int i = 0; i < N; i++) {        if (R == K) {            break;        }Â
        // Stores the maximum right bound        // where left bound ? R        int maxr = R;Â
        int j;Â
        // Iterate in the range [i+1, N-1]        for (j = i + 1; j < N; j++) {Â
            // If the starting point of j-th            // element is less than equal to R            if (arr[j].first <= R) {Â
                maxr = max(maxr, arr[j].second);            }Â
            // Otherwise            else {                break;            }        }Â
        i = j - 1;        R = maxr;        ans++;    }Â
    // If the right bound    // is not equal to K    if (R != K) {        return -1;    }Â
    // Otherwise    else {        return ans;    }}Â
// Driver Codeint main(){    // Given Input    int K = 4;    vector<pair<int, int> > arr{ { 0, 6 } };Â
    // Function Call    cout << MinimumPairs(arr, K);} |
Java
// Java Program for above approachimport java.io.*;import java.lang.*;import java.util.*;Â
// User defined Pair classclass Pair {Â Â Â Â int x;Â Â Â Â int y;Â
    // Constructor    public Pair(int x, int y)    {        this.x = x;        this.y = y;    }}// class to sort the elements in// increasing order of left element and// sort pairs with equal left element in// decreasing order of right elementclass cmp implements Comparator<Pair> {Â
    public int compare(Pair p1, Pair p2)    {        if (p1.x == p2.x)         {            return p1.y - p2.y;        }        else        {            return p2.x - p1.x;        }    }}Â
class GFG {    // Function to select minimum number of pairs    // such that it covers the entire range [0, K]    public static int MinimumPairs(Pair arr[], int K)    {        int N = arr.length;        // Sort the array using comparator        Arrays.sort(arr, new cmp());Â
        // If the start element        // is not equal to 0        if (arr[0].x != 0)         {            return -1;        }Â
        // Stores the minimum        // number of pairs required        int ans = 1;Â
        // Stores the right bound of the range        int R = arr[0].y;Â
        // Iterate in the range[0, N-1]        for (int i = 0; i < N; i++)         {            if (R == K)             {                break;            }Â
            // Stores the maximum right bound            // where left bound is less than equal to R            int maxr = R;            int j;Â
            // Iterate in the range [i+1, N-1]            for (j = i + 1; j < N; j++)             {Â
                // If the starting point of j-th                // element is less than equal to R                if (arr[j].x <= R)                 {Â
                    maxr = Math.max(maxr, arr[j].y);                }Â
                // Otherwise                else                {                    break;                }            }Â
            i = j - 1;            R = maxr;            ans++;        }Â
        // If the right bound        // is not equal to K        if (R != K)         {            return -1;        }Â
        // Otherwise        else        {            return ans;        }    }Â
    // Driver code    public static void main(String[] args)    {        int K = 4;        int n = 1; // length of array        Pair arr[] = new Pair[n];        arr[0] = new Pair(0, 6);Â
        System.out.println(MinimumPairs(arr, K));    }}Â
// This code is contributed by rj13to. |
Python3
# Python3 program for the above approachÂ
# Function to select minimum number of pairs# such that it covers the entire range [0, K]def MinimumPairs(arr, K):Â Â Â Â Â Â Â Â Â N = len(arr)Â
    # Sort the array using comparator    arr.sort()Â
    # If the start element    # is not equal to 0    if (arr[0][0] != 0):        return -1Â
    # Stores the minimum    # number of pairs required    ans = 1Â
    # Stores the right bound of the range    R = arr[0][1]Â
    # Iterate in the range[0, N-1]    for i in range(N):        if (R == K):            breakÂ
        # Stores the maximum right bound        # where left bound ? R        maxr = RÂ
        j = 0Â
        # Iterate in the range [i+1, N-1]        for j in range(i + 1, N, 1):                         # If the starting point of j-th            # element is less than equal to R            if (arr[j][0] <= R):                maxr = max(maxr, arr[j][1])Â
            # Otherwise            else:                breakÂ
        i = j - 1        R = maxr        ans += 1Â
    # If the right bound    # is not equal to K    if (R != K):        return -1Â
    # Otherwise    else:        return ansÂ
# Driver Codeif __name__ == '__main__':         # Given Input    K = 4    arr = [ [ 0, 6 ] ]Â
    # Function Call    print(MinimumPairs(arr, K))Â
# This code is contributed by bgangwar59 |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Function to select minimum number of pairs// such that it covers the entire range [0, K]function MinimumPairs(arr, K){Â Â Â Â Â Â Â Â Â let N = arr.lengthÂ
    // Sort the array using comparator    arr.sort((a,b)=>a-b)Â
    // If the start element    // is not equal to 0    if (arr[0][0] != 0)        return -1Â
    // Stores the minimum    // number of pairs required    let ans = 1Â
    // Stores the right bound of the range    let R = arr[0][1]Â
    // Iterate in the range[0, N-1]    for(let i=0;i<N;i++){        if(R == K)            breakÂ
    //    // Stores the maximum right bound    //    // where left bound ? R        let maxr = RÂ
        let j = 0Â
        // Iterate in the range [i+1, N-1]        for(j=i+1;j<N;j++){                         // If the starting point of j-th            // element is less than equal to R            if (arr[j][0] <= R)                maxr = Math.max(maxr, arr[j][1])Â
            // Otherwise            else break        }Â
        i = j - 1        R = maxr        ans += 1Â
    }Â
    // // If the right bound    // // is not equal to K    if(R != K)        return -1Â
    // Otherwise    else        return ans}Â
// Driver Code     // Given Inputlet K = 4let arr = [ [ 0, 6 ] ]Â
// Function Calldocument.write(MinimumPairs(arr, K),"</br>")Â
// This code is contributed by shinjanpatraÂ
Â
</script> |
C#
// C# program for the above approachÂ
using System;using System.Linq;using System.Collections.Generic;Â
// User defined Pair classpublic class Pair{Â Â Â Â public int x;Â Â Â Â public int y;Â
Â
    // Constructor    public Pair(int x, int y)    {        this.x = x;        this.y = y;    }}Â
// class to sort the elements in// increasing order of left element and// sort pairs with equal left element in// decreasing order of right elementpublic class cmp : IComparer<Pair>{Â
    public int Compare(Pair p1, Pair p2)    {        if (p1.x == p2.x)        {            return p2.y - p1.y;        }        else        {            return p1.x - p2.x;        }    }}Â
Â
class GFG{    // Function to select minimum number of pairs    // such that it covers the entire range [0, K]    public static int MinimumPairs(Pair[] arr, int K)    {        int N = arr.Length;        // Sort the array using comparator        Array.Sort(arr, new cmp());                  // If the start element        // is not equal to 0        if (arr[0].x != 0)        {            return -1;        }             // Stores the minimum        // number of pairs required        int ans = 1;             // Stores the right bound of the range        int R = arr[0].y;             // Iterate in the range[0, N-1]        for (int i = 0; i < N; i++)        {            if (R == K)            {                break;            }                 // Stores the maximum right bound            // where left bound is less than equal to R            int maxr = R;            int j;                 // Iterate in the range [i+1, N-1]            for (j = i + 1; j < N; j++)            {                     // If the starting point of j-th                // element is less than equal to R                if (arr[j].x <= R)                {                         maxr = Math.Max(maxr, arr[j].y);                }                     // Otherwise                else                {                    break;                }            }                 i = j - 1;            R = maxr;            ans++;        }             // If the right bound        // is not equal to K        if (R != K)        {            return -1;        }             // Otherwise        else        {            return ans;        }    }         // Driver code    public static void Main(string[] args)    {        int K = 4;        int n = 1; // length of array        Pair[] arr = new Pair[n];        arr[0] = new Pair(0, 6);             Console.WriteLine(MinimumPairs(arr, K));    }}Â
// This code is contributed by Harshad |
-1
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More to that Topic: geeksforgeeks.org/minimum-number-of-pairs-required-to-be-selected-to-cover-a-given-range/ […]
… [Trackback]
[…] Here you can find 61367 additional Info on that Topic: geeksforgeeks.org/minimum-number-of-pairs-required-to-be-selected-to-cover-a-given-range/ […]