Array Disjoint check

Problem :

Given an integer array of size N. Write a Program to find whether Arrays are disjoint or not. Two arrays are said to be disjoint if they have no elements in common.

Example 1:

Sample input 1:

4

2 -4 -1 -3

3

1 3 5

Sample output 1:

Disjoint.

Example 2:

Sample input 2:

5

1 5 -7 6 3

4

2 4 6 8

Sample output 2:

Not disjoint. ( 6 is common)

Explanation:

When we solve these problems, multiple methods come to our minds, such as the brute force method. However, using it results in very high time complexity. Therefore, we can use the inbuilt methods in Java such as Collections.disjoint(c1, c2). It returns true if the collections are disjoint; otherwise, it returns false. The main problem here is that we need to convert the array to any collection. Let us convert it into an ArrayList. There are three methods available to convert an array to an ArrayList. In the below solution, I used the foreach loop to convert it from an array to an ArrayList. Finally, you need to pass the two ArrayLists to the disjoint method.

Solution:

import java.util.*;

public class Day54 {

    public static void main(String[] args) {

        System.out.println("Enter the length of 1st array :");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int[] arr1 = new int[n];
        for(int i=0; i<n; i++)
        {
            arr1[i]= sc.nextInt();
        }

        System.out.println("Enter the length of 2nd array :");
        int n2 = sc.nextInt();

        int[] arr2 = new int[n2];
        for(int i=0; i<n2; i++)
        {
            arr2[i]= sc.nextInt();
        }

        List<Integer> list1 = new ArrayList<>();
        for(Integer i:arr1) {
            list1.add(i);
        }

        List<Integer> list2 = new ArrayList<>();
        for(Integer j:arr2) {
            list2.add(j);
        }

        if(Collections.disjoint(list1, list2))
            System.out.println("Disjoint.");
        else
            System.out.println("Not disjoint.");
    }
}

Did you find this article valuable?

Support DHANRAJ NIKAM by becoming a sponsor. Any amount is appreciated!