4

How can we find out missing elements from two arrays ? Ex:

        int []array1 ={1,2,3,4,5};           
        int []array2 ={3,1,2};

From the above two arrays i want to find what are the missing elements in second array?

2
  • If you already know some programming/computer science, I'd go with the answers that aren't mine. If you're just learning, try to write out all the code yourself so you understand it. Commented Feb 5, 2010 at 14:07
  • 1
    Are you allowed duplicate values in either array? Commented Feb 5, 2010 at 14:09

10 Answers 10

5

Convert them to Sets and use removeAll.

The first problem is how to convert a primitive int[] to a collection. With Guava you can use:

List<Integer> list1 = Ints.asList(array1);
List<Integer> list2 = Ints.asList(array2);

Apache commons (which I'm not familiar with) apparently has something similar.

Now convert to a set:

Set<Integer> set1 = new HashSet<Integer>(list1);

And compute the difference:

set1.removeAll(list2);

And convert the result back to an array:

return Ints.toArray(set1);
Sign up to request clarification or add additional context in comments.

1 Comment

This assumes that there are no duplicates allowed in either array.
2

If you are allowed duplicates in the arrays, an efficient (O(n)) solution it to create a frequency table (Map) by iterating over the first array, and then use the map to match off any elements in the second array.

Map<Integer, Integer> freqMap = new HashMap<Integer, Integer>();

// Iterate over array1 and populate frequency map whereby
// the key is the integer and the value is the number of
// occurences.
for (int val1 : array1) {
  Integer freq = freqMap.get(val1);

  if (freq == null) {
    freqMap.put(val1, 1);
  } else {
    freqMap.put(val1, freq + 1);
  }
}

// Now read the second array, reducing the frequency for any value
// encountered that is also in array1.
for (int val2 : array2) {
  Integer freq = freqMap.get(val2);

  if (freq == null) {
    freqMap.remove(val2);
  } else {
    if (freq == 0) {
      freqMap.remove(val2);   
    } else {
      freqMap.put(freq - 1);
    }
  }
}

// Finally, iterate over map and build results.
List<Integer> result = new LinkedList<Integer>();

for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
  int remaining = entry.getValue();

  for (int i=0; i<remaining; ++i) {
    result.add(entry.getKey());
  }
}

// TODO: Convert to int[] using the util. method of your choosing.

Comments

2

Simple logic for getting the unmatched numbers.

public static int getelements(int[] array1, int[] array2)
{
    int count = 0;
    ArrayList unMatched = new ArrayList();
    int flag = 0;
    for(int i=0; i<array1.length ; i++)
    {   flag=0;
        for(int j=0; j<array2.length ; j++)
        {
                if(array1[i] == array2[j]) {
                    flag =1;
                    break;
                }


        }
        if(flag==0)
        {
            unMatched.add(array1[i]);
        }
    }

        System.out.println(unMatched);

    return unMatched.size();

}

public static  void  main(String[] args) {
// write your code here5

    int array1[] = {7,3,7,2,8,3,2,5};
    int array2[] = {7,4,9,5,5,10,4};


    int count;
    count = getelements(array1,array2);

    System.out.println(count);



}

2 Comments

Please explain what your code does and how it does it.
Method getelements takes 2 arrays.. Now using 2 loops will help to compare elements of array 1 with elements of array 2. Then if the condition is matched I am breaking that loop. And inserting it into array list because duplicates are allowed. That's it.
0

You can use Set and its methods. This operation would be a set difference.

Comments

0

The naive way would be to simply search one array for each of the elements of the other array (with a for loop). If you first were to SORT both arrays, it becomes much more efficient.

Comments

0

Consider using intersection method:

A healthy discussion is available at:

http://www.coderanch.com/t/35439/Programming-Diversions/Intersection-two-arrays

Comments

0

You could create two other int arrays to store the multiplicity of each value. Increment the index of the array that the value corresponds with every time it is found and then compare the arrays.

It's not the most "efficient" way perhaps, but it's a very simple concept that works.

Comments

0

Guava library can be helpful; you need to change Array in Set then can use API.

Comments

0

@finnw I believe you were thinking of commons-collections. Need to import org.apache.commons.collections.CollectionUtils; To get the disjunction function.

Using the disjunction method will find all objects that aren't found in an intersection.

Integer[] array1 ={1,2,3,4,5};           
Integer[] array2 ={3,1,2};
List list1 = Arrays.asList(array1);
List list2 = Arrays.asList(array2);
Collection result = CollectionUtils.disjunction(list1, list2);
System.out.println(result); // displays [4, 5]

2 Comments

I was thinking of a method that converts int[] either to Integer[] or to List<Integer>. I did not know about disjunction (I don't think it has an equivalent in Guava yet.)
@finnw I don't think there is one for List<Integer> but commons-lang's has ArrayUtils.toObject(int[] array) that returns Integer[].
0

This is not the most efficient way but it's probably the simplest way that works in Java :

public static void main(final String[] args) {
        final int[] a = { 1, 2, 3, 4, 5 };
        final int[] b = { 3, 1, 2 };
        // we have to do this just in case if there might some values that are missing in a and b
        // example: a = { 1, 2, 3, 4, 5 }; b={ 2, 3, 1, 0, 5 }; missing value=4 and 0
        findMissingValue(b, a);
        findMissingValue(a, b);
    }

    private static void findMissingValue(final int[] x, final int[] y) {
        // loop through the bigger array
        for (final int n : x) {
            // for each value in the a array call another loop method to see if it's in there
            if (!findValueSmallerArray(n, y)) {
                System.out.println("missing value: " + n);
                // break;
            }
        }
    }

    private static boolean findValueSmallerArray(final int n, final int[] y) {
        for (final int i : y) {
            if (n == i) {
                return true;
            }
        }
        return false;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.