How to check if two given sets are disjoint?

Given two sets represented by two arrays, how to check if the given two sets are disjoint or not? It may be assumed that the given arrays have no duplicates.

Difficulty Level: Rookie

Input: set1[] = {12, 34, 11, 9, 3}
       set2[] = {2, 1, 3, 5}
Output: Not Disjoint
3 is common in two sets.

Input: set1[] = {12, 34, 11, 9, 3}
       set2[] = {7, 2, 1, 5}
Output: Yes, Disjoint
There is no common element in two sets.

We strongly recommend to minimize your browser and try this yourself first.
There are plenty of methods to solve this problem, it’s a good test to check how many solutions you can guess.

Method 1 (Simple)
Iterate through every element of first set and search it in other set, if any element is found, return false. If no element is found, return tree. Time complexity of this method is O(mn).

Following is implementation of above idea.



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple C++ program to check if two sets are disjoint
#include<iostream>
using namespace std;
  
// Returns true if set1[] and set2[] are disjoint, else false
bool areDisjoint(int set1[], int set2[], int m, int n)
{
    // Take every element of set1[] and search it in set2
    for (int i=0; i<m; i++)
      for (int j=0; j<n; j++)
         if (set1[i] == set2[j])
            return false;
  
    // If no element of set1 is present in set2
    return true;
}
  
// Driver program to test above function
int main()
{
    int set1[] = {12, 34, 11, 9, 3};
    int set2[] = {7, 2, 1, 5};
    int m = sizeof(set1)/sizeof(set1[0]);
    int n = sizeof(set2)/sizeof(set2[0]);
    areDisjoint(set1, set2, m, n)? cout << "Yes" : cout << " No";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if two sets are disjoint
  
public class disjoint1 
{
    // Returns true if set1[] and set2[] are 
    // disjoint, else false
    boolean aredisjoint(int set1[], int set2[]) 
    {
         // Take every element of set1[] and 
         // search it in set2
        for (int i = 0; i < set1.length; i++) 
        {
            for (int j = 0; j < set2.length; j++) 
            {
                if (set1[i] == set2[j])
                    return false;
            }
        }
        // If no element of set1 is present in set2
        return true;
    }
      
    // Driver program to test above function
    public static void main(String[] args) 
    {
        disjoint1 dis = new disjoint1();
        int set1[] = { 12, 34, 11, 9, 3 };
        int set2[] = { 7, 2, 1, 5 };
  
        boolean result = dis.aredisjoint(set1, set2);
        if (result)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Rishabh Mahrsee

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Simple python 3 program to check
# if two sets are disjoint
  
# Returns true if set1[] and set2[] are disjoint, else false
def areDisjoint(set1, set2, m, n):
    # Take every element of set1[] and search it in set2
    for i in range(0, m):
        for j in range(0, n):
            if (set1[i] == set2[j]):
                return False
  
    # If no element of set1 is present in set2
    return True
  
  
# Driver program
set1 = [12, 34, 11, 9, 3]
set2 = [7, 2, 1, 5]
m = len(set1)
n = len(set2)
print("yes") if areDisjoint(set1, set2, m, n) else(" No")
  
# This code ia contributed by Smitha Dinesh Semwal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if two 
// sets are disjoint 
using System;
  
class GFG
{
// Returns true if set1[] and set2[] 
// are disjoint, else false 
public virtual bool aredisjoint(int[] set1, 
                                int[] set2)
{
    // Take every element of set1[] 
    // and search it in set2 
    for (int i = 0; i < set1.Length; i++)
    {
        for (int j = 0; 
                 j < set2.Length; j++)
        {
            if (set1[i] == set2[j])
            {
                return false;
            }
        }
    }
      
    // If no element of set1 is 
    // present in set2 
    return true;
}
  
// Driver Code
public static void Main(string[] args)
{
    GFG dis = new GFG();
    int[] set1 = new int[] {12, 34, 11, 9, 3};
    int[] set2 = new int[] {7, 2, 1, 5};
  
    bool result = dis.aredisjoint(set1, set2);
    if (result)
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
  
// This code is contributed by Shrikant13

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A Simple PHP program to check 
// if two sets are disjoint
  
// Returns true if set1[] and set2[] 
// are disjoint, else false
function areDisjoint($set1, $set2, $m, $n)
{
    // Take every element of set1[]
    // and search it in set2
    for ($i = 0; $i < $m; $i++)
    for ($j = 0; $j < $n; $j++)
        if ($set1[$i] == $set2[$j])
            return false;
  
    // If no element of set1 is 
    // present in set2
    return true;
}
  
// Driver Code
$set1 = array(12, 34, 11, 9, 3);
$set2 = array(7, 2, 1, 5);
$m = sizeof($set1);
$n = sizeof($set2);
if(areDisjoint($set1, $set2,
               $m, $n) == true)
    echo "Yes";
else
    echo " No";
  
// This code is contributed
// by Akanksha Rai
?>

chevron_right



Output :

Yes

Method 2 (Use Sorting and Merging)
1) Sort first and second sets.
2) Use merge like process to compare elements.

Following is implementation of above idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple C++ program to check if two sets are disjoint
#include<iostream>
#include<algorithm>
using namespace std;
  
// Returns true if set1[] and set2[] are disjoint, else false
bool areDisjoint(int set1[], int set2[], int m, int n)
{
    // Sort the given two sets
    sort(set1, set1+m);
    sort(set2, set2+n);
  
    // Check for same elements using merge like process
    int i = 0, j = 0;
    while (i < m && j < n)
    {
        if (set1[i] < set2[j])
            i++;
        else if (set2[j] < set1[i])
            j++;
        else /* if set1[i] == set2[j] */
            return false;
    }
  
    return true;
}
  
// Driver program to test above function
int main()
{
    int set1[] = {12, 34, 11, 9, 3};
    int set2[] = {7, 2, 1, 5};
    int m = sizeof(set1)/sizeof(set1[0]);
    int n = sizeof(set2)/sizeof(set2[0]);
    areDisjoint(set1, set2, m, n)? cout << "Yes" : cout << " No";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if two sets are disjoint
  
import java.util.Arrays;
  
public class disjoint1 
{
    // Returns true if set1[] and set2[] are 
    // disjoint, else false
    boolean aredisjoint(int set1[], int set2[]) 
    {
        int i=0,j=0;
          
        // Sort the given two sets
        Arrays.sort(set1);
        Arrays.sort(set2);
          
        // Check for same elements using 
        // merge like process
        while(i<set1.length && j<set2.length)
        {
            if(set1[i]<set2[j])
                i++;
            else if(set1[i]>set2[j])
                j++;
            else 
                return false;
              
        }
        return true;
    }
  
    // Driver program to test above function
    public static void main(String[] args) 
    {
        disjoint1 dis = new disjoint1();
        int set1[] = { 12, 34, 11, 9, 3 };
        int set2[] = { 7, 2, 1, 5 };
  
        boolean result = dis.aredisjoint(set1, set2);
        if (result)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}
  
// This code is contributed by Rishabh Mahrsee

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Simple Python 3 program to check
# if two sets are disjoint
  
# Returns true if set1[] and set2[]
# are disjoint, else false
def areDisjoint(set1, set2, m, n):
    # Sort the given two sets
    set1.sort()
    set2.sort()
  
    # Check for same elements  
    # using merge like process
    i = 0; j = 0
    while (i < m and j < n):
          
        if (set1[i] < set2[j]):
            i += 1
        elif (set2[j] < set1[i]):
            j += 1
        else: # if set1[i] == set2[j] 
            return False
    return True
  
  
# Driver Code
set1 = [12, 34, 11, 9, 3]
set2 = [7, 2, 1, 5]
m = len(set1)
n = len(set2)
  
print("Yes") if areDisjoint(set1, set2, m, n) else print("No")
  
# This code is contributed by Smitha Dinesh Semwal

chevron_right



Output :

Yes

Time complexity of above solution is O(mLogm + nLogn).

The above solution first sorts both sets, then takes O(m+n) time to find intersection. If we are given that the input sets are sorted, then this method is best among all.

Method 3 (Use Sorting and Binary Search)
This is similar to method 1. Instead of linear search, we use Binary Search.
1) Sort first set.
2) Iterate through every element of second set, and use binary search to search every element in first set. If element is found return it.

Time complexity of this method is O(mLogm + nLogm)

Method 4 (Use Binary Search Tree)
1) Create a self balancing binary search tree (Red Black, AVL, Splay, etc) of all elements in first set.
2) Iterate through all elements of second set and search every element in the above constructed Binary Search Tree. If element is found, return false.
3) If all elements are absent, return true.

Time complexity of this method is O(mLogm + nLogm).



Method 5 (Use Hashing)
1) Create an empty hash table.
2) Iterate through the first set and store every element in hash table.
3) Iterate through second set and check if any element is present in hash table. If present, then return false, else ignore the element.
4) If all elements of second set are not present in hash table, return true.

Following are the implementation of this method.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<bits/stdc++.h>
using namespace std;
  
/* C++ program to check if two sets are distinct or not */
// This function prints all distinct elements
bool areDisjoint(int set1[], int set2[], int n1, int n2)
{
    // Creates an empty hashset
    set<int> myset;
  
    // Traverse the first set and store its elements in hash
    for (int i = 0; i < n1; i++)
        myset.insert(set1[i]);
  
    // Traverse the second set and check if any element of it
    // is already in hash or not.
    for (int i = 0; i < n2; i++)
        if (myset.find(set2[i]) != myset.end())
            return false;
  
    return true;
}
  
// Driver method to test above method
int main()
{
    int set1[] = {10, 5, 3, 4, 6};
    int set2[] = {8, 7, 9, 3};
  
    int n1 = sizeof(set1) / sizeof(set1[0]);
    int n2 = sizeof(set2) / sizeof(set2[0]);
    if (areDisjoint(set1, set2, n1, n2))
        cout << "Yes";
    else
        cout << "No";
}
//This article is contributed by Chhavi

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Java program to check if two sets are distinct or not */
import java.util.*;
  
class Main
{
    // This function prints all distinct elements
    static boolean areDisjoint(int set1[], int set2[])
    {
        // Creates an empty hashset
        HashSet<Integer> set = new HashSet<>();
  
        // Traverse the first set and store its elements in hash
        for (int i=0; i<set1.length; i++)
            set.add(set1[i]);
  
        // Traverse the second set and check if any element of it
        // is already in hash or not.
        for (int i=0; i<set2.length; i++)
            if (set.contains(set2[i]))
                return false;
  
        return true;
    }
  
    // Driver method to test above method
    public static void main (String[] args)
    {
        int set1[] = {10, 5, 3, 4, 6};
        int set2[] = {8, 7, 9, 3};
        if (areDisjoint(set1, set2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

using System;
using System.Collections.Generic;
  
/* C# program to check if two sets are distinct or not */
  
public class GFG
{
    // This function prints all distinct elements 
    public static bool areDisjoint(int[] set1, int[] set2)
    {
        // Creates an empty hashset 
        HashSet<int> set = new HashSet<int>();
  
        // Traverse the first set and store its elements in hash 
        for (int i = 0; i < set1.Length; i++)
        {
            set.Add(set1[i]);
        }
  
        // Traverse the second set and check if any element of it 
        // is already in hash or not. 
        for (int i = 0; i < set2.Length; i++)
        {
            if (set.Contains(set2[i]))
            {
                return false;
            }
        }
  
        return true;
    }
  
    // Driver method to test above method 
    public static void Main(string[] args)
    {
        int[] set1 = new int[] {10, 5, 3, 4, 6};
        int[] set2 = new int[] {8, 7, 9, 3};
        if (areDisjoint(set1, set2))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
//This code is contributed by Shrikant13

chevron_right



Output:

No

Time complexity of the above implementation is O(m+n) under the assumption that hash set operations like add() and contains() work in O(1) time.

This article is contributed by Rajeev. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : shrikanth13, Akanksha_Rai



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.