# java program to find missing numbers in an array

0

Most frequently asked interview question specially in banking and telecom domain. Interviewer wants to check your logical analysis and problem solving skills by asking these types of questions. Sometimes you will get the signature of the methods and your job is to complete that methods for example, I faced an interview with one of the world's largest telecom domain company, where there is a question sheet with signature of the methods as given below.

```public static int[] findMissingNumbers(int[] numArray, int firstNum,int lastNum) {}
```

Description: Complete the above method to find all the missing numbers from an sorted array. The numArray is an sorted array and firstNum is the starting number from an array and the lastNum is the last number in an numArray. For example, if numArray is like 3,4,5,6,8,10 and firstNum is 1 and the lastNum is 10 then out put would be an array of 1,2,7,9.

Well there is a lots of way to solve this problem, and here we are going to use one of them.

Number.java

```package com.javamakeuse.poc;

public class Number {

public static int[] findingMissingNumbers(int[] numArray, int firstNum,
int lastNum) {
int[] missingNumbers = {}; // To keep the missing numbers.
StringBuilder missingNumberBuilder = new StringBuilder();

if (numArray != null && numArray.length > 0) {
// Before the First number in the array
for (int i = 1; i < numArray; i++) {
missingNumberBuilder.append(i + " ");
}
for (int i = 1; i < numArray.length; i++) {
for (int j = 1 + numArray[i - 1]; j < numArray[i]; j++) {
missingNumberBuilder.append(j + " ");
}
}
// Missing numbers between numArray[numArray.length-1] and last
// number
for (int i = 1 + numArray[numArray.length - 1]; i <= lastNum; i++) {
missingNumberBuilder.append(i + " ");
}
String[] missingNumberArray = {};
if (!missingNumberBuilder.toString().equals("")) {
missingNumberArray = missingNumberBuilder.toString().split(" ");
missingNumbers = new int[missingNumberArray.length];
for (int i = 0; i < missingNumberArray.length; i++) {
missingNumbers[i] = Integer.parseInt(missingNumberArray[i]);
}
}
}
return missingNumbers;

}

public static void main(String[] args) {
int []  inputNnumbers = { 3,4,5,6,8,10 };

// verifying the method
int [] outputNnumbers = findingMissingNumbers(inputNnumbers, 1, 10);

// printing the missing numbers
for (int i = 0; i < outputNnumbers.length; i++) {
System.out.println(outputNnumbers[i]);
}
}
}

```

Out put: 1 2 7 9

That's it :)