How to use Nested Loops In Javascript
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
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)
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
Contact Us