Finding Arrays are Disjoint or Not in Java
Understanding Disjoint Arrays
Two arrays are said to be disjoint if they have no elements in common.
We will explore three different methods to check if two arrays are disjoint in Java.
Method 1: Using Nested Loops
This method iterates through both arrays and checks for common elements.
import java.util.*; public class DisjointArrays { static boolean areDisjoint(int[] arr1, int[] arr2) { for (int i : arr1) { for (int j : arr2) { if (i == j) { return false; } } } return true; } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {5, 6, 7, 8}; if (areDisjoint(arr1, arr2)) { System.out.println("Arrays are disjoint"); } else { System.out.println("Arrays are not disjoint"); } } }
Arrays are disjoint
Method 2: Using Hashing
This method uses a HashSet to check for common elements efficiently.
import java.util.*; public class DisjointArrays { static boolean areDisjoint(int[] arr1, int[] arr2) { Setset = new HashSet<>(); for (int num : arr1) { set.add(num); } for (int num : arr2) { if (set.contains(num)) { return false; } } return true; } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {5, 6, 7, 8}; if (areDisjoint(arr1, arr2)) { System.out.println("Arrays are disjoint"); } else { System.out.println("Arrays are not disjoint"); } } }
Arrays are disjoint
Method 3: Using Set Intersection
This method uses set operations to determine if two arrays are disjoint.
import java.util.*; import java.util.stream.Collectors; public class DisjointArrays { static boolean areDisjoint(int[] arr1, int[] arr2) { Setset1 = Arrays.stream(arr1).boxed().collect(Collectors.toSet()); Set set2 = Arrays.stream(arr2).boxed().collect(Collectors.toSet()); set1.retainAll(set2); return set1.isEmpty(); } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {5, 6, 7, 8}; if (areDisjoint(arr1, arr2)) { System.out.println("Arrays are disjoint"); } else { System.out.println("Arrays are not disjoint"); } } }
Arrays are disjoint