You are given an integer array containing 1 to n but one of the number from 1 to n in the array is missing. You need to provide optimum solution to find the missing number. Number can not be repeated in the array.
For Example
int[] arr1 = {1, 5, 4, 2}; 3 is missing
int[] arr1 = {7, 5, 4, 1, 2, 3}; 6 is missing
package com.seleniumtest;
public class MissingNumber
{
public void findMissingNumber(int[] inputArray)
{
//Increment by 1, total number will be one more than array size because 1 number is missing in array
int n = inputArray.length + 1;
int sum = n * (n+1) / 2;
int restSum = 0;
for(int i = 0; i < inputArray.length; i++)
{
restSum += inputArray[i];
}
int missingNumber = sum - restSum;
System.out.println("Missing Number is:" +missingNumber);
}
public static void main(String args[])
{
int[] arr = {7, 5, 4, 1, 2, 3};
MissingNumber mn = new MissingNumber();
mn.findMissingNumber(arr);
}
}
Comments