JavaScript Program to Find if Arrays are Disjoint or Not

Given two arrays, Our task is to check if the given two arrays are disjoint or not. Disjoint arrays in JavaScript are arrays that have no elements in common

Input: arr1[] = [12, 34, 11, 9, 3]
arr2[] = [2, 1, 3, 5]
Output: Not Disjoint
3 is common in two sets.
Input: arr1[] = [12, 34, 11, 9, 3]
arr2[] = [7, 2, 1, 5]
Output: Yes, Disjoint
There is no common element in two sets.

Table of Content

  • Use array.some()
  • Using Set
  • Using Nested Loops

Use array.some()

The array.some() method checks if any element in one array exists in the other array.If any common element is found, it returns false, indicating that the arrays are not disjoint. Otherwise, it returns true.

Example: Implementation of program to find whether arrays are disjoint or not using Array.some() method

JavaScript
const disjoint = (a, b) => !a.some(e => b.includes(e));

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
console.log("Are arrays disjoint:", disjoint(arr1, arr2));

Output
Are arrays disjoint: true

Time Complexity: O(n*m),where n is the length of arr1 and m is the length of arr2.

Auxiliary Space: O(1)

Using Set

The Set method converts one array into a Set and then iterates through the other array to check if any element exists in the Set. If any common element is found, it returns false, indicating that the arrays are not disjoint. Otherwise, it returns true.

Example: Implementation of program to find whether arrays are disjoint or not using Set

JavaScript
const disjoint = (a, b) => {
    const set = new Set(a);
    for (const e of b) {
        if (set.has(e)) return false;
    }
    return true;
};

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
console.log("Are arrays disjoint:", disjoint(arr1, arr2));

Output
Are arrays disjoint: true

Time Complexity: O(n+m),where n is the length of arr1 and m is the length of arr2.

Auxiliary Space: O(n)

Using Nested Loops

In this approach we use Nested Loop to iterating through each element of one array and comparing it with every element of the other array. If any common element is found, it returns false, indicating that the arrays are not disjoint. Otherwise, it returns true.

Example: Implementation of program to find whether arrays are disjoint or not using Nested Loops

JavaScript
const disjoint = (a, b) => {
    for (let i = 0; i < a.length; i++) {
        for (let j = 0; j < b.length; j++) {
            if (a[i] === b[j]) return false;
        }
    }
    return true;
};

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
console.log("Are arrays disjoint:", disjoint(arr1, arr2));

Output
Are arrays disjoint: true

Time Complexity: O(n*m),where n is the length of arr1 and m is the length of arr2.

Auxiliary Space: O(1)