Open In App

How to check if two given sets are disjoint?

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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 the first set and search it in another set, if any element is found, return false. If no element is found, return true. The time complexity of this method is O(mn).

Following is the implementation of the above idea.

C++




// A Simple C++ program to check if two sets are disjoint
#include<bits/stdc++.h>
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;
}


Java




// 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


Python




# 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


C#




// 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


Javascript




<script>
 
// Javascript program to check if two sets are disjoint   
     
    // Returns true if set1[] and set2[] are
    // disjoint, else false
    function aredisjoint(set1,set2)
    {
        // Take every element of set1[] and
         // search it in set2
        for (let i = 0; i < set1.length; i++)
        {
            for (let 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
    let set1=[12, 34, 11, 9, 3];
    let set2=[7, 2, 1, 5];
    result = aredisjoint(set1, set2);
    if (result)
        document.write("Yes");
    else
        document.write("No");
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


PHP




<?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
?>


Output

Yes





Time Complexity: O(m*n)
Auxiliary Space: O(1),As constant extra space is used.

Method 2 (Use Sorting and Merging) :

  1. Sort first and second sets. 
  2. Use merge like the process to compare elements.

Following is the implementation of the above idea.

C++




// A Simple C++ program to check if two sets are disjoint
#include<bits/stdc++.h>
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;
}


Java




// 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


Python3




# 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


C#




// C# program to check if two sets are disjoint
using System;
 
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
        Array.Sort(set1);
        Array.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 code
    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)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
 
// Javascript program to check if two
// sets are disjoint
 
// Returns true if set1[] and set2[] are
// disjoint, else false
function aredisjoint(set1, set2)
{
    let i = 0, j = 0;
     
    // Sort the given two sets
    set1.sort(function(a, b){return a - b});
    set2.sort(function(a, b){return a - b});
     
    // 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 code
let set1 = [ 12, 34, 11, 9, 3 ];
let set2 = [ 7, 2, 1, 5 ];
result = aredisjoint(set1, set2);
 
if (result)
    document.write("YES");
else
    document.write("NO");
 
// This code is contributed by rag2127
 
</script>


Output

Yes





Time Complexity: O(m*log m + n*log n), The above solution first sorts both sets and then takes O(m+n) time to find the intersection. If we are given that the input sets are sorted, then this method is best among all.
Auxiliary Space: O(1), As constant extra space is used.

Method 3 (Use Sorting and Binary Search):
This is similar to method 1. Instead of a linear search, we use Binary Search

  1. Sort first set.
  2. Iterate through every element of the second set, and use binary search to search every element in the first set. If an element is found return it.

Below is the implementation of the approach:

C++




// C++ program to check if two sets are disjoint
 
#include<bits/stdc++.h>
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 set1 array
      sort(set1, set1+ m);
       
    // Take every element of set2[] and search
      // it in the sorted set1 array
    for (int i=0; i<n; i++) {
      // binary search to find lower bound
      // of set2[i] in set1
      int lb = lower_bound(set1, set1+n, set2[i]) - set1;
       
      // if element is present in set1
      // return false
      if(lb < n && set1[lb] == set2[i])
        return false;
    }
   
    // If no element of set2 is present in set1
    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;
}


Java




import java.util.Arrays;
 
public class Main {
 
    // Returns true if set1[] and set2[] are disjoint, else false
    static boolean areDisjoint(int[] set1, int[] set2, int m, int n) {
        // Sort the set1 array
        Arrays.sort(set1);
 
        // Take every element of set2[] and search it in the sorted set1 array
        for (int i = 0; i < n; i++) {
            // Binary search to find the lower bound of set2[i] in set1
            int lb = Arrays.binarySearch(set1, set2[i]);
 
            // If the element is present in set1, return false
            if (lb >= 0)
                return false;
        }
 
        // If no element of set2 is present in set1, return true
        return true;
    }
 
    // Driver program to test the above function
    public static void main(String[] args) {
        int[] set1 = {12, 34, 11, 9, 3};
        int[] set2 = {7, 2, 1, 5};
        int m = set1.length;
        int n = set2.length;
        System.out.println(areDisjoint(set1, set2, m, n) ? "Yes" : "No");
    }
}
// This code is contributed by rambabuguphka


Python3




# Function to check if two sets are disjoint
def are_disjoint(set1, set2):
    # Convert the sets to lists and sort set1
    set1.sort()
     
    # Iterate through elements in set2
    for elem in set2:
        # Use binary search (bisect) to find the lower bound of elem in set1
        index = bisect_left(set1, elem)
         
        # If element is present in set1, they are not disjoint
        if index < len(set1) and set1[index] == elem:
            return False
     
    # If no element of set2 is present in set1, they are disjoint
    return True
 
from bisect import bisect_left
 
# Driver program to test the function
if __name__ == "__main__":
    set1 = [12, 34, 11, 9, 3]
    set2 = [7, 2, 1, 5]
    if are_disjoint(set1, set2):
        print("Yes")
    else:
        print("No")


C#




// C# program to check if two sets are disjoint
using System;
 
public class GFG {
    // Returns true if set1[] and set2[]
    // are disjoint, else false
    static bool AreDisjoint(int[] set1, int[] set2, int m,
                            int n)
    {
        // sort the set1 array
        Array.Sort(set1);
 
        // Take every element of set2[] and search
        // it in the sorted set1 array
        for (int i = 0; i < n; i++) {
            // binary search to find lower bound
            // of set2[i] in set1
            int lb = Array.BinarySearch(set1, set2[i]);
 
            // if element is present in set1
            // return false
            if (lb >= 0)
                return false;
        }
 
        // If no element of set2 is present in set1
        return true;
    }
 
    // Driver program to test above function
    public static void Main(string[] args)
    {
        int[] set1 = { 12, 34, 11, 9, 3 };
        int[] set2 = { 7, 2, 1, 5 };
        int m = set1.Length;
        int n = set2.Length;
        Console.WriteLine(
            AreDisjoint(set1, set2, m, n) ? "Yes" : "No");
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Function to check if two sets are disjoint
function areDisjoint(set1, set2) {
    // Sort the set1 array
    set1.sort((a, b) => a - b);
 
    // Iterate through each element of set2 and search it in the sorted set1 array
    for (let i = 0; i < set2.length; i++) {
        // Binary search to find the lower bound of set2[i] in set1
        let lb = lowerBound(set1, set2[i]);
 
        // If the element is present in set1, return false
        if (lb < set1.length && set1[lb] === set2[i]) {
            return false;
        }
    }
 
    // If no element of set2 is present in set1, return true
    return true;
}
 
// Binary search to find the lower bound of x in the array arr
function lowerBound(arr, x) {
    let low = 0, high = arr.length;
    while (low < high) {
        let mid = Math.floor((low + high) / 2);
        if (arr[mid] < x) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }
    return low;
}
 
// Driver program to test the function
let set1 = [12, 34, 11, 9, 3];
let set2 = [7, 2, 1, 5];
 
// Check if two sets are disjoint
areDisjoint(set1, set2) ? console.log("Yes") : console.log("No");


Output

Yes





The time complexity of this method is O(mLogm + nLogm)

Space Complexity: O(1) as no extra space has been taken.

Method 4 (Use Binary Search Tree):

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

The time complexity of this method is O(m*log m + n*log m). 

Method 5 (Use Hashing):

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

The following is the implementation of this method.  

C++




/* C++ program to check if two sets are distinct or not */
#include<bits/stdc++.h>
using namespace std;
 
// 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


Java




/* 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");
    }
}


Python3




# Python3 program to
# check if two sets are
# distinct or not
# This function prints
# all distinct elements
def areDisjoint(set1, set2,
                n1, n2):
   
  # Creates an empty hashset
  myset = set([])
   
  # Traverse the first set
  # and store its elements in hash
  for i in range (n1):
    myset.add(set1[i])
     
  # Traverse the second set
  # and check if any element of it
  # is already in hash or not.
  for i in range (n2):
    if (set2[i] in myset):
      return False
  return True
 
# Driver method to test above method
if __name__ == "__main__":
   
  set1 = [10, 5, 3, 4, 6]
  set2 = [8, 7, 9, 3]
 
  n1 = len(set1)
  n2 = len(set2)
   
  if (areDisjoint(set1, set2,
                  n1, n2)):
    print ("Yes")
  else:
    print("No")
 
# This code is contributed by Chitranayal


C#




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


Javascript




<script>
/* Javascript program to check if two sets are distinct or not */
 
 // This function prints all distinct elements
function areDisjoint(set1,set2)
{
    // Creates an empty hashset
        let set = new Set();
  
        // Traverse the first set and store its elements in hash
        for (let 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 (let i = 0; i < set2.length; i++)
            if (set.has(set2[i]))
                return false;
  
        return true;
}
 
// Driver method to test above method
let set1 = [10, 5, 3, 4, 6];
let set2 = [8, 7, 9, 3];
if (areDisjoint(set1, set2))
    document.write("Yes");
else
    document.write("No");
 
// This code is contributed by ab2127
</script>


Output

No





Time Complexity: O(m+n) under the assumption that hash set operations like add() and contains() work in O(1) time.
Auxiliary Space: O(n), The extra space is used to store the elements in the set.

Method 6: Using inbuilt function 

C++




#include <iostream>
#include <unordered_set>
using namespace std;
 
bool areDisjoint(int arr1[], int n1, int arr2[], int n2)
{
    unordered_set<int> set1(arr1, arr1 + n1);
    unordered_set<int> set2(arr2, arr2 + n2);
    unordered_set<int> result;
    for (int x : set1) {
        if (set2.find(x) != set2.end()) {
            result.insert(x);
        }
    }
    if (result.size() != 0) {
        return false;
    }
    else {
        return true;
    }
}
 
int main()
{
    int arr1[] = { 10, 5, 3, 4, 6 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int arr2[] = { 8, 7, 9, 3 };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    if (areDisjoint(arr1, n1, arr2, n2)) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
    return 0;
}


Java




// Import necessary Java libraries
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
public class DisjointArrays {
    public static boolean areDisjoint(int[] arr1, int n1,
                                      int[] arr2, int n2)
    {
 
        // Create HashSet objects for arr1 and arr2
        Set<Integer> set1 = new HashSet<Integer>();
        for (int i = 0; i < n1; i++) {
            set1.add(arr1[i]);
        }
 
        Set<Integer> set2 = new HashSet<Integer>();
        for (int i = 0; i < n2; i++) {
            set2.add(arr2[i]);
        }
 
        // Create a HashSet to store common elements
        Set<Integer> result = new HashSet<Integer>();
        for (int x : set1) {
            if (set2.contains(x)) {
                result.add(x);
            }
        }
 
        // If result set is not empty, then arrays are not
        // disjoint
        if (!result.isEmpty()) {
            return false;
        }
        else {
            return true;
        }
    }
 
    public static void main(String[] args)
    {
 
        int[] arr1 = { 10, 5, 3, 4, 6 };
        int n1 = arr1.length;
 
        int[] arr2 = { 8, 7, 9, 3 };
        int n2 = arr2.length;
 
        // Check if arrays are disjoint
        if (areDisjoint(arr1, n1, arr2, n2)) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}


Python3




def areDisjoint(arr1, arr2):
  set1 = set(arr1)
  set2 = set(arr2)
  result = set1.intersection(set2)
  if len(result) != 0:
    return False
  else:
    return True
arr1 = [10, 5, 3, 4, 6]
arr2 = [8, 7, 9, 3]
if areDisjoint(arr1, arr2):
  print("YES")
else:
  print("NO")
 
# This code is contributed by Prince Kumar


C#




using System;
using System.Collections.Generic;
 
class Program {
    // Method to check if two arrays are disjoint
    static bool AreDisjoint(int[] arr1, int[] arr2) {
        // Create hash sets from the input arrays
        HashSet<int> set1 = new HashSet<int>(arr1);
        HashSet<int> set2 = new HashSet<int>(arr2);
        // Initialize an empty hash set to store common elements
        HashSet<int> result = new HashSet<int>();
        // Iterate through elements of set1
        foreach (int x in set1) {
            // If x is present in set2, add it to result
            if (set2.Contains(x)) {
                result.Add(x);
            }
        }
        // If result is empty, the arrays are disjoint
        return result.Count == 0;
    }
 
    static void Main(string[] args) {
        // Define example arrays
        int[] arr1 = { 10, 5, 3, 4, 6 };
        int[] arr2 = { 8, 7, 9, 3 };
        // Check if the arrays are disjoint
        if (AreDisjoint(arr1, arr2)) {
            Console.WriteLine("YES");
        }
        else {
            Console.WriteLine("NO");
        }
    }
}


Javascript




function areDisjoint(arr1, n1, arr2, n2) {
    // Create sets from the two input arrays
    let set1 = new Set(arr1);
    let set2 = new Set(arr2);
 
    // Check for common elements
    for (let x of set1) {
        if (set2.has(x)) {
            return false;
        }
    }
    return true;
}
 
let arr1 = [10, 5, 3, 4, 6];
let n1 = arr1.length;
let arr2 = [8, 7, 9, 3];
let n2 = arr2.length;
 
if (areDisjoint(arr1,n1,arr2,n2)) {
    console.log("YES");
} else {
    console.log("NO");
}


Output

NO





Time Complexity: O(min(n, m)), where n = length of arr1, m = length of arr2

Auxiliary Space: O(max(n, m))



Previous Article
Next Article

Similar Reads

Find two disjoint good sets of vertices in a given graph
Given an undirected unweighted graph with N vertices and M edges. The task is to find two disjoint good sets of vertices. A set X is called good if for every edge UV in the graph at least one of the endpoint belongs to X(i.e, U or V or both U and V belong to X). If it is not possible to make such sets then print -1. Examples: Input : Output : {1 3
8 min read
Make two sets disjoint by removing minimum elements
Given two sets of integers as two arrays of size m and n. Find count of minimum numbers that should be removed from the sets so that both set become disjoint or don't contains any elements in common. We can remove elements from any set. We need to find minimum total elements to be removed. Examples : Input : set1[] = {20, 21, 22} set2[] = {22, 23,
9 min read
Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: Input: n = 4, k = 2, arr[] = {10, 10, 11, 11 }, brr
8 min read
Number of K's such that the given array can be divided into two sets satisfying the given conditions
Given an array arr[] of size N. The task is to find the number of K's such that the array can be divided into two sets containing equal number of elements if elements less than K are in one set and the rest of them are in the other set. Note: N is always even. Examples: Input: arr[] = {9, 1, 4, 4, 6, 7} Output: 2 {1, 4, 4} and {6, 7, 9} are the two
4 min read
Find maximum number of edge disjoint paths between two vertices
Given a directed graph and two vertices in it, source 's' and destination 't', find out the maximum number of edge disjoint paths from s to t. Two paths are said edge disjoint if they don't share any edge. There can be maximum two edge disjoint paths from source 0 to destination 7 in the above graph. Two edge disjoint paths are highlighted below in
15+ min read
Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
Given a connected acyclic graph, a source vertex and a destination vertex, your task is to count the number of vertices between the given source and destination vertex by Disjoint Union Method . Examples: Input : 1 4 4 5 4 2 2 6 6 3 1 3 Output : 3 In the input 6 is the total number of vertices labeled from 1 to 6 and the next 5 lines are the connec
10 min read
Check if a Binary String can be split into disjoint subsequences which are equal to "010"
Given a binary string, S of size N, the task is to check if it is possible to partition the string into disjoint subsequences equal to "010". Examples: Input: S = "010100"Output: YesExplanation: Partitioning the string in the manner 010100 to generate two subsequences equal to "010". Input: S = "010000"Output: No Approach: The idea is based on the
8 min read
Count of ways to select exactly K non-disjoint ranges from given N ranges
Given two arrays L[] and R[] of size N, and an integer K, the task is to find the number of ways to select exact K disjoint ranges formed by taking elements present at the same index from the array L[] and R[]. Examples: Input: N = 7, K = 3, L[] = {1, 3, 4, 6, 1, 5, 8}, R[] = {7, 8, 5, 7, 3, 10, 9}Output: 9Explanation: The possible ways of selectin
10 min read
Queries to update Subarrays of a given Array using Disjoint Set
Given an array arr[] consisting of N integers, consisting only of 0's initially and queries Q[][] of the form {L, R, C}, the task for each query is to update the subarray [L, R] with value C. Print the final array generated after performing all the queries. Examples: Input: N = 5, Q = {{1, 4, 1}, {3, 5, 2}, {2, 4, 3}} Output: 1 3 3 3 2 Explanation:
10 min read
Count all disjoint pairs having absolute difference at least K from a given array
Given an array arr[] consisting of N integers, the task is to count all disjoint pairs having absolute difference of at least K. Note: The pair (arr[i], arr[j]) and (arr[j], arr[i]) are considered as the same pair. Examples: Input: arr[] = {1, 3, 3, 5}, K = 2Output: 2Explanation:The following two pairs satisfy the necessary conditions: {arr[0], arr
13 min read
Article Tags :
Practice Tags :