Share on Google+Share on Google+

Find a missing element from array

In this section, you will learn how to find a missing element from the array.

Find a missing element from array

We have two arrays A and B where B consists of all the elements that are present in A but one element is missing from the array B. From these two arrays, we have to find the missing element from the second array i.e from B. For this, we have calculated the sum of elements from both the arrays and subtract them. The result will be the missing element.

Here is the code:

import java.util.*;

class CompareArrays {
	public static void main(String[] args) {
		int[] A = { 1, 2, 3, 4, 5 };
		int[] B = { 3, 1, 2, 5 };
		int i, n = 5, sum1 = 0, sum2 = 0;
		for (i = 0; i <= n - 1; i++) {
			sum1 = sum1 + A[i];
			if (i <= n - 2) {
				sum2 = sum2 + B[i];
		System.out.println("Missing Element is: " + (sum1 - sum2));


Missing Element is: 4


Posted on: July 2, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.