Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check if there exists a pair (a, b) such that for all the N pairs either of the element should be equal to either a or b

  • Difficulty Level : Hard
  • Last Updated : 20 Jul, 2021

Given an array arr[] of N pairs of distinct integers, the task is to check if there exists any pair (X, Y) such that each pair of the array has at least one common element with the pair (X, Y).

Examples:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}
Output: Yes
Explanation:
One of the pair that satisfies the condition is (2, 4).



Input: arr[] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}}
Output: No
Explanation:
No pair satisfies the conditions.

Approach: The given problem can be solved based on the following observations:

  1. It can be observed that if there exists a pair (X, Y), then either arr[0].first will be equal to either X or Y, or arr[0].second will be equal to either X or Y.
  2. As each pair has distinct elements, then if an element occurs X times in X pairs, then it must exist in all the pairs.
  3. Therefore, if (P, Q) is the pair needed, and F is the count of pairs with no element common to P, then Q will be equal to an element which will occur F times in the pair where no element is common to P.

. Follow the steps below to solve the problem:

  • Initialize an integer variable, say counter, to count the number of pairs where both the elements of the pair are not equal to X.
  • Also, initialize a vector say frequency to store the frequency of the elements.
  • Initialize a variable X as arr[0].first.
  • Now traverse the array arr[], using the variable i, and perform the following steps:
    • If arr[i].first and arr[i].second both are not equal to X, then the increment count of arr[i].first and arr[i].second in the vector frequency and then increment counter by 1.
  • If the maximum frequency of the array frequency is equal to the counter, then print “Yes” and return.
  • Otherwise, assign arr[0].second to X and then again perform the above steps.
  • Finally, after completing the above steps, if none of the above cases satisfy, then print “No“.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether there exists
// a pair with given condition
string CommonPairs(int N, vector<pair<int, int> > arr)
{
    vector<int> V = { arr[0].first, arr[0].second };
 
    for (int x : V) {
      
 
        // Stores the frequency of elements
        vector<int> frequency(N + 1, 0);
 
        // Stores the count of the number
        // of pairs with no element equal
        // to x
        int counter = 0;
 
        // Traverse the array arr[]
        for (auto c : arr) {
            // If both the elements are not
            // equal to x
            if (c.first != x && c.second != x) {
 
                // Increment count of c.first
                // c.second by 1
                frequency++;
                frequency++;
 
                // Increment count by 1
                counter++;
            }
        }
 
        int M = *max_element(frequency.begin(),
                             frequency.end());
 
        // If maximum frequency is equal to counter
        if (M == counter) {
            return "Yes";
        }
    }
 
    // Return No
    return "No";
}
 
// Driver Code
int main()
{
    // Given Input
    vector<pair<int, int> > arr
        = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 } };
    int N = arr.size();
 
    // Function Call
    cout << CommonPairs(N, arr);
}

Python3




# python 3 program for the above approach
 
# Function to check whether there exists
# a pair with given condition
def CommonPairs(N,  arr):
 
    V = (arr[0][0], arr[0][1])
 
    for x in V:
 
        # Stores the frequency of elements
        frequency = [0] * (N + 2)
 
        # Stores the count of the number
        # of pairs with no element equal
        # to x
        counter = 0
 
        # Traverse the array arr[]
        for c in arr:
           
            # If both the elements are not
            # equal to x
            if (c[0] != x and c[1] != x):
 
                # Increment count of c.first
                # c.second by 1
                frequency] += 1
                frequency] += 1
 
                # Increment count by 1
                counter += 1
 
        M = max(frequency)
 
        # If maximum frequency is equal to counter
        if (M == counter):
            return "Yes"
 
    # Return No
    return "No"
 
# Driver Code
if __name__ == "__main__":
   
    # Given Input
    arr = [[1, 2], [2, 3], [3, 4], [4, 5]]
    N = len(arr)
 
    # Function Call
    print(CommonPairs(N, arr))
 
    # This code is contributed by ukasp.

Javascript




<script>
// Javascript program for the above approach
 
// Function to check whether there exists
// a pair with given condition
function CommonPairs(N, arr) {
 
    let V = [arr[0][0], arr[0][1]];
 
    for (let x of V) {
 
 
        // Stores the frequency of elements
        let frequency = new Array(N + 1).fill(0);
 
        // Stores the count of the number
        // of pairs with no element equal
        // to x
        let counter = 0;
 
        // Traverse the array arr[]
        for (let c of arr) {
            // If both the elements are not
            // equal to x
            if (c[0] != x && c[1] != x) {
 
                // Increment count of c[0]
                // c[1] by 1
                frequency]++;
                frequency]++;
 
                // Increment count by 1
                counter++;
            }
        }
 
        let M = [...frequency].sort((a, b) => b - a)[0];
 
        // If maximum frequency is equal to counter
        if (M == counter) {
            return "Yes";
        }
    }
 
    // Return No
    return "No";
}
 
// Driver Code
 
// Given Input
let arr = [[1, 2], [2, 3], [3, 4], [4, 5]];
let N = arr.length;
 
// Function Call
document.write(CommonPairs(N, arr));
 
// This code is contributed by gfgking.
</script>
Output
Yes

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!