How to Find Missing Number From Integer Array

In this example, we’ll find missing number from Integer array but this method works only with a set of integers that are sorted and are in sequence like below:

This is a common question asked in Java Interviews.

Input:
int[] arr1 = { 1, 2, 3, 5, 6, 7 };
Output:
4

1. Java

public class FindMissingNumberFromIntegerArray {

	public static void main(String[] args) {
		FindMissingNumberFromIntegerArray obj = new FindMissingNumberFromIntegerArray();
		int arr[] = { 1, 2, 3, 4, 6, 7, 9, 8, 10, 11, 12, 13, 14, 15 };
		System.out.println(obj.findMissing(arr, 15));
	}

	public int findMissing(int[] arr, int num) {

		int expectedSum = num * (num + 1) / 2;
		int actualSum = 0;

		for (int i = 0; i < arr.length; i++) {
			actualSum += arr[i];
		}

		return expectedSum - actualSum;
	}

}

Output:

5

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions