Java Online Compiler
Example: DisjointArrayHashSet in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// DisjointArrayHashSet import java.util.HashSet; import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if two integer arrays are disjoint using a HashSet. * @param arr1 The first array. * @param arr2 The second array. * @return true if the arrays are disjoint (no common elements), false otherwise. */ public static boolean areArraysDisjointHashSet(int[] arr1, int[] arr2) { // Step 1: Create a HashSet to store elements from the first array. HashSet<Integer> set = new HashSet<>(); // Step 2: Add all elements of arr1 to the HashSet. for (int element : arr1) { set.add(element); } // Step 3: Iterate through each element of the second array. for (int element : arr2) { // Step 4: Check if the current element from arr2 exists in the HashSet. if (set.contains(element)) { // Step 5: If it exists, a common element is found, so arrays are not disjoint. return false; } } // Step 6: If no common elements are found after checking all elements of arr2, the arrays are disjoint. return true; } public static void main(String[] args) { // Test Case 1: Disjoint arrays int[] arr1_case1 = {1, 2, 3}; int[] arr2_case1 = {4, 5, 6}; System.out.println("Arrays: {1, 2, 3} and {4, 5, 6}"); System.out.println("Are disjoint (HashSet)? " + areArraysDisjointHashSet(arr1_case1, arr2_case1)); // Expected: true // Test Case 2: Non-disjoint arrays int[] arr1_case2 = {1, 2, 3}; int[] arr2_case2 = {3, 4, 5}; System.out.println("\nArrays: {1, 2, 3} and {3, 4, 5}"); System.out.println("Are disjoint (HashSet)? " + areArraysDisjointHashSet(arr1_case2, arr2_case2)); // Expected: false // Test Case 3: Empty arrays int[] arr1_case3 = {}; int[] arr2_case3 = {1, 2, 3}; System.out.println("\nArrays: {} and {1, 2, 3}"); System.out.println("Are disjoint (HashSet)? " + areArraysDisjointHashSet(arr1_case3, arr2_case3)); // Expected: true } }
Output
Clear
ADVERTISEMENTS