Menu Close

COMMON ELEMENTS BETWEEN TWO ARRAYS

Write a program to find common elements between two arrays.
You should not use any inbuilt methods are list to find common values

Input: size of two array,Input two arrays .
Output: print the common elements.

TEST CASE 1
INPUT
8
8
11 78 23 90 10 34 19 56
45 23 12 56 90 17 78 33
OUTPUT
78
23
90
56


TEST CASE 2
INPUT
6
6
12 32 56 23 11 19
21 2 67 12 32 11
OUTPUT
12
32
11

import java.io.*;
import java.util.*;
public class temp{
  public static void main(String[] args){
    Scanner x = new Scanner(System.in);
    List<Integer> l1 = new ArrayList<Integer>();
    List<Integer> l2 = new ArrayList<Integer>();
    List<Integer> common = new ArrayList<Integer>();
    System.out.printf("Enter n number Arr1: ");
    int x1 = x.nextInt();
    System.out.printf("Enter n number Arr2: ");
    int x2 = x.nextInt();

    System.out.printf("Enter Arr1: ");
    for(int i = 0; i < x1; i++)
        l1.add(x.nextInt());
    System.out.printf("Enter Arr2: ");
    for(int i = 0; i < x2; i++)
        l2.add(x.nextInt());
    for(int e: l1)
        if(l2.contains(e))
            common.add(e);
    for(int e: common)
        System.out.println("Common: "+e);
    }
}

OUTPUT:

Input:
Enter n number Arr1: 3
Enter n number Arr2: 2
Enter Arr1: 12 25 36
Enter Arr2: 36 66
Output:
Common: 36

Input:
Enter n number Arr1: 4
Enter n number Arr2: 3
Enter Arr1: 22 25 101 25
Enter Arr2: 63 101 22 0
Output:
Common: 22
Common: 101

Input:
Enter n number Arr1: 1
Enter n number Arr2: 1
Enter Arr1: 5
Enter Arr2: 6
Output:
NIL

Input:
Enter n number Arr1: 5
Enter n number Arr2: 6
Enter Arr1: 5 25 63 62 12
Enter Arr2: 3 6 9 12 15 18
Output:
Common: 12

SCrnshot