2 Comments


  1. I have a better solution in bigo n
    But u have to use extra space biho n space
    Just store all element of first array in hash map than traverse second array and find each element from hash map in bigo 1 time and if item found in array then print this……..
    Thanks

    Reply

  2. Provided that every array do not contain duplicates, another approach is using a Set:

    int[] arr1 = { 5, 4, 1, 6, 2 };
    int[] arr2 = { 6, 8, 2, 3, 7 };

    Set set = new HashSet();
    for (int i: arr1){
    set.add(i);
    }

    List list = new ArrayList();
    for (int i: arr2) {
    if (set.contains(i)) {
    list.add(i);
    }
    }
    System.out.println(list);

    With the first loop you put all the elements of the first array into the Set and with the second loop you just check if each element of the second array is contained in the Set: if it’s true, it means that the number is contained in both the arrays and so it’s added to the result list.
    The runtime complexity is lowered to O(max(n,m)) but the space complexity is raised to linear O(n), where n is the size of first array and m is the size of the second array.

    Reply

Leave a Reply