Java Program To Find Missing Numbers
Java Program To Find Missing Numbers
Let's understand the problem statement, we have numbers from 1 to 100 that are put
into an integer array, what's the best way to find out which number is missing? If
Interviewer especially mention 1 to 100 then you can apply the above trick about sum
of the series, as shown below as well. If it has more than one missing element than
you can use BitSet class, of-course only if your interviewer allows it.
1) Sum of the series : Formula : n (n+1)/2( but only work for one missing number)
2) Use BitSet, if array has more than one missing elements.
I have provided BitSet solution with another purpose, to introduce with this nice
utility class. In many interviews I have asked about this class to Java developers, but
many of them not even aware of this. I think this problem is nice way to learn how to
use BitSet in Java as well.
import java.util.Arrays;
import java.util.BitSet;
/**
* Java program to find missing elements in a Integer array containing
* numbers from 1 to 100.
*
* @author Javin Paul
*/
public class MissingNumberInArray {
public static void main(String args[]) {
// one missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
// two missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
// three missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
// four missing number
printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
5
Missing numbers in integer array [1, 2, 3, 4, 6, 9, 8], with total number 10
is
5
7
10
Missing numbers in integer array [1, 2, 3, 4, 9, 8], with total number 10 is
5
6
7
10
Missing number in array [1, 2, 3, 5] is 4