How to Find Missing Number on Integer Array of 1 to 100 - BitSet Example

One of the most frequently asked question on programming interviews is, write a program to find the missing number in an array in Java, C# or any other language; depending upon which language you choose. This kind of coding interview questions are not only asked in small start-ups but also on some of the biggest technical companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. Simplest version of this question is to find missing elements in an area of 100 integers, which contains numbers between 1 and 100. This can easily be solved by calculating the sum of the series using n(n+1)/2, and this is also one of the quickest and efficient ways, but it cannot be used if the array contains more than one missing numbers or if the array contains duplicates.

This gives interviewer some nice follow-up questions to check whether a candidate can apply his knowledge of the slightly different condition or not. So if you get through this, they will ask you to find the missing number in an array of duplicates. This might be tricky but you will soon find out that another way to find missing and duplicate number in the array is to sort it.

In a sorted array, you can compare whether a number is equal to expected next number or not. Alternatively, you can also use BitSet in Java to solve this problem.




Java Program to find missing numbers

Java Program to find Missing number in Array
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 mentions 1 to 100 then you can apply the above trick about the sum of the series as shown below as well. If it has more than one missing element that 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 an array has more than one missing elements.

I have provided a 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 a nice way to learn how to use BitSet in Java as well.

By the way, if you are going for interview, then apart from this question, its also good to know how to find duplicate number in array and program to find second highest number in an integer array. More often than not, those are asked as follow-up question after this.


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);
 
        // Only one missing number in array
        int[] iArray = new int[]{1, 2, 3, 5};
        int missing = getMissingNumber(iArray, 5);
        System.out.printf("Missing number in array %s is %d %n"
                           Arrays.toString(iArray), missing);
    }

   /**
    * A general method to find missing values from an integer array in Java.
    * This method will work even if array has more than one missing element.
    */
    private static void printMissingNumber(int[] numbers, int count) {
        int missingCount = count - numbers.length;
        BitSet bitSet = new BitSet(count);
 
        for (int number : numbers) {
            bitSet.set(number - 1);
        }
 
        System.out.printf("Missing numbers in integer array %s, with total number %d is %n",
        Arrays.toString(numbers), count);
        int lastMissingIndex = 0;

        for (int i = 0; i < missingCount; i++) {
            lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
            System.out.println(++lastMissingIndex);
        }
 
    }

   /**
    * Java method to find missing number in array of size n containing
    * numbers from 1 to n only.
    * can be used to find missing elements on integer array of 
    * numbers from 1 to 100 or 1 - 1000
    */
    private static int getMissingNumber(int[] numbers, int totalCount) {
        int expectedSum = totalCount * ((totalCount + 1) / 2);
        int actualSum = 0;
        for (int i : numbers) {
            actualSum += i;
        }
 
        return expectedSum - actualSum;
    }
 
}
 
Output
Missing numbers in integer array [1, 2, 3, 4, 6], with total number 6 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 7, 9, 8, 10], with total number 10 is
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

You can see that how using a right data structure can solve the problem easily. This is the key takeaway of this program, for the more coding question, you can check the Cracking the Coding Interviews, a collection of 189 coding questions from programming interviews of tech companies like Google, Amazon, Microsoft and others.



That's all on this program to find missing element in an array of 100 elements. As I said, it's good to know the trick, which just require you to calculate sum of numbers and then subtract that from actual sum, but you can not use that if array has more than one missing numbers. On the other hand, BitSet solution is more general, as you can use it to find more than one missing values on integer array. For more programming questions, you can also check here.

19 comments :

SARAL SAXENA said...

@Javin..really cool one , lem me add more for developers :)
This was an Amazon interview question ....
Solution for that it was ....
1) Calculate the sum of all numbers stored in the array of size 51.
2) Subtract the sum from (52 * 53)/2 ---- Formula : n * (n + 1) / 2.

but anyways I have also come up with the approach that uses XOR..

We can use XOR operation which is safer than summation because in programming languages if the given input is large it may overflow and may give wrong answer.

Before going to the solution A xor A = 0 so if we xor two identical number the value is Zero.

// Assuming that the array contains 99 distinct integers between 1..99 and empty slot value is zero
for(int i=0;i<100;i++)
{
if(ARRAY[i] != 0)
XOR ^= ARRAY[i];
XOR ^= (i + 1);
}
return XOR;

Anonymous said...

@Saral, what is the initial value of XOR here, I am guess it's zero, right?

Anonymous said...

There are many ways to search an element in array :
1) linear search involves comparing each element to expected value, complexity O(n)
2) If array is sorted then you can also use binary search, compexity O(logN)

I would prefer binary search because of it's performance.

Ankit Verma said...

class FindMissingElement
{
void printMissingElement(int[] numbers,int totalelement)
{
int i=0;
boolean missingElement;
while(i<totalelement)
{
missingElement=true; // initialized to true means element is missing.
for(int j=0;j<numbers.length;j++)
{
if(totalelement==numbers[j]) // each array element with totalelement.
{
missingElement=false; // means element is not missing.
}
}
if(missingElement==true)
{
System.out.println(totalelement);
}
--totalelement;
}
}
public static void main(String args[])
{
int elements[]=new int[]{2,4,7,5}; // integer array
FindMissingElement me=new FindMissingElement();
me.printMissingElement(elements,7); // passing array element and total element.
}
}

Javin Paul said...

hello @Ankit, I guess your forgot to put the output of your program, nice solution though.

JAVA said...

private static void findMissingNumber(int[] number){
for (int i = 0; i < number.length -1; i++) {
int j = i+1;
int difference = number[j] - number[i] ;
if(difference != 1){
int missing_num = number[i] + 1;
for (int k = difference; k > 1 ; k--) {
System.out.println("Missing Number is " + missing_num);
missing_num++;
}
}
}
}

Anonymous said...

hi java i think ur solution will not work ...if array is not sorted......for ex: int [] a={ 1,6,5,3,4}

Anonymous said...

package practice;
import static java.lang.System.*;
public class arr1 {

public static void main(String[] args)
{
int [] a ={1,7,3,5,6,8,10,9};
int l=a.length;
int c=1;

//SORT THE ARRAY
for(int i=0;ia[i+1])
{
int temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}


//CHECK FOR MISSING
for(int i=0;i<l;i++)
{
if(a[i]!=c)
{
out.println(c+" " + "not present");
c=c+2;
}
else
c++;

}
// TODO Auto-generated method stub

}

}

Anonymous said...

Why not just add all the number, and subtract the calculate sum with expected sum, if array doesn't contain any duplicates then result is your missing number. This logic will work in any programming language e.g. Go, Rust, Ruby, Python, C, C++ or even JavaScript, becasue it doesn't use language specifice feature, like JDK class BitSet

Anonymous said...

void printMissingElement(final int[] numbers, int totalelement) {
List asList = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
asList.add(numbers[i]);
}

while (totalelement >= 1) {
if (!asList.contains(totalelement)) {
System.out.println("missing element : " + totalelement);
}
totalelement--;

}
}

Thangavel Loganathan said...

Hello Guys,

I have a one more solution for the same problem, which is more efficient way because the code has XOR operation,


public class MissingElementsInArray {

public static void main(String[] args) {

int [] a = {1,3,4,5};
System.out.println("The Value is :"+findMissingNumberInSequentialArray(a));
}

public static int findMissingNumberInSequentialArray(int[] a){
int xorCalulated = 1;
for(int i=2;i<=a.length;i++) // this loop runs (n) times
xorCalulated^=i;

int xorActual=a[0];
for(int i=1;i<(a.length-1);i++) // this loop runs (n-1) times. Since there is one element "missing"
xorActual^=a[i];

return xorActual^xorCalulated;

}

}

thewolf said...

In Java you must force to decimal operation in ((totalCount + 1) / 2) because the result here is 60, the correct operation in Java is

int expectedSum = (int) (totalCount * ((float) (totalCount + 1) / 2));

Praveen Sharma said...

check this

public class FindNumber
{

public static float findNumber(int[] number,float count)
{

float expectedsum =count*((count+1)/2);
System.out.println(expectedsum);
float acsum=0;
for (float i:number)
{
acsum+=i;
}

return expectedsum -acsum;

}
public static void main(String[] args) {
System.out.println(findNumber(new int[]{1,2,3,4,6},6));

}

}

it type int then wrong answer so we should take float type

seeloju rajesh said...

How is it
class MissingElement
{
public static void main(String []args){
int[] a={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,19,20};
int i,j,c;
for(i=1;i<a.length;i++){

if((a[i]-a[i-1])!=1){
c=a[i+1]-1;
System.out.println(" Missing element is : "+c);

}


}
}
}

Nayan Jyoti Gogoi said...

Hi Rajesh,

I think c=a[i+1]-1; should be c=a[i-1]+1;
And thank you for the post

Unknown said...

Hi,

I couldnt get you BitSet solution,


Also i have something implemented and working :)


// {2,3,6,7,8} //8
private static void printMissingNumbers(int[] number,int count){
int missingCounts=count - number.length;
int countAllMissings=0;

for(int i=1;i<count;i++){

if(number[i-1-countAllMissings] != i){
System.out.println("missing number " + i);
countAllMissings++;
}

}

}

Anurag said...

Comment by Wolf is correct, Method getMissingNumber(int[] numbers, int totalCount) is not giving correct result for all case. it must be changed as below.

int expectedSum = (int) (totalCount * ((float) (totalCount + 1) / 2));

Read more: http://javarevisited.blogspot.com/2014/11/how-to-find-missing-number-on-integer-array-java.html#ixzz4In9UvFTk


Arun kumar said...

Int[] input={121,122,123,124,125,126,127,128,129};
Output should be:{123,124,125,126,127,128,129}
Since 121 and 122 as repeated number. 121 has two 1's and 122 as two 2's so that two number should be removed. Any one suggest me the code.

Anonymous said...

public class MissedElmtInArry {

public static void main(String[] args) {
int i,sum=0, expsum=0,n=5;
int a[]={1,2,4,5};
for(i=0;i<4;i++)
sum=sum+a[i];
System.out.println("Actual Sum: "+sum);
expsum = n*((n+1)/2);
System.out.println("result:"+(expsum-sum));
}
}

Post a Comment