It's been a long time since I have discussed any coding or algorithm interview questions, so I thought to revisit one of the most popular array based coding problem of finding missing numbers in a given array of integers. You might have heard or seen this problem before on your programming job interviews and you might already know how to solve this problem. But, there are a lot of different versions of this problem with increasing difficulty levels which interviewers normally use to confuse candidate and further test their ability to adapt to frequent changes. In the past I have demonstrated how to find the missing number in a sorted array as well on the unsorted integer array in Java using BitSet (see here), but, with just one missing number and without any duplicates, which kinda make those problems a bit easier.

That makes the problem somewhat easy but what do you do if interviewer tells you that

##
1.

You have given an integer array of size N. Array contains numbers from 1 to N-1 but a couple of numbers are missing in an array which also contains duplicates.

Write a Java program to print the missing number from the sequence.

For example, if given array is {1, 1, 2, 3, 5, 5, 7, 9, 9, 9} then it has length 10 and contains a number from 1 to 9. In this case, missing numbers are 4, 6, and 8.

##
2.

When you see the question is to

In this case, we need to use a different approach, something like a

The teacher has a register with names of all students, he goes through the list and mark absences on red. We can use the same approach to find all the missing numbers in the list.

We can use an array as register and it's an index as names of the numbers. You need to loop through the given array and tick marking all the numbers which are present by storing one of their respective indices. For example, if the first number in the given array is 5 (since the array is not sorted) then we store 1 on index 5 e.g. register[5] = 1

Once we have gone through all the numbers is given, we can go through our register array and print all the indices where the value is zero.

This solution is also safe from duplicates because if a number comes once or twice we just store 1 on the respective index.

Btw, if you are not familiar with array and essential data structure e.g. linked list, binary tree, and hash table, I suggest you to first go through

##
3.

Now that we know how to solve this problem of missing numbers in

This is the simplest Java program to solve this problem. You can see that

The code is exactly same as a solution, we created another array by copying length from original array and used it mark numbers which are present.

Since array indices are also integer and they are in the range of input values we can leverage them to use both as data and metadata. Had the array contains a number which is not in the range of 1 to N-1 then we couldn't have used an array. If you want to know more about array data structure, you can also see

Here is the summary of algorithm and code in a slide for better understanding:

##
4.

Now, the time is to analyze our solution to find the CPU and Memory complexity using Big O notation. If you look at the code then you will find that we are creating another array with the same size which means it has memory or

This means if the array is too big like contains all the numbers in the integer range then we would a lot more memory which may not be available and our program could throw OutOfMemoryError in Java. This is even more possible because array needs a contiguous chunk of memory.

So, if we can remove the additional array which is not really holding anything and find a way to just store missing number which is quite less than the all the number that we can improve this solution, something for you guys to think.

For

We can further improve this solution if we

That's all about this classic

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

Cracking the Coding Interview: 189 Problems and Solutions

Other

Thanks for reading this article so far. If you like this coding or algorithm interview question and my explanation then please share with your friends and colleagues. If you have any doubt or feedback then please drop a note.

That makes the problem somewhat easy but what do you do if interviewer tells you that

*array contains duplicates*and*more than one numbers are missing?*Well, that's what we'll discuss in this article, but before that let's get the problem statement correctly.##
1. __Problem Statement__

You have given an integer array of size N. Array contains numbers from 1 to N-1 but a couple of numbers are missing in an array which also contains duplicates.Write a Java program to print the missing number from the sequence.

For example, if given array is {1, 1, 2, 3, 5, 5, 7, 9, 9, 9} then it has length 10 and contains a number from 1 to 9. In this case, missing numbers are 4, 6, and 8.

##
2. __Solution__

When you see the question is to **find missing number in array**, you might think about our earlier solution of calculating the sum of all the numbers and deducting it from expected sum to find the missing number, but unfortunately that will not work in this situation because*more than one number is missing*as well it contains duplicates.In this case, we need to use a different approach, something like a

**roll-call**you would have seen in your school.The teacher has a register with names of all students, he goes through the list and mark absences on red. We can use the same approach to find all the missing numbers in the list.

We can use an array as register and it's an index as names of the numbers. You need to loop through the given array and tick marking all the numbers which are present by storing one of their respective indices. For example, if the first number in the given array is 5 (since the array is not sorted) then we store 1 on index 5 e.g. register[5] = 1

Once we have gone through all the numbers is given, we can go through our register array and print all the indices where the value is zero.

*These are absentees or missing numbers.*This solution is also safe from duplicates because if a number comes once or twice we just store 1 on the respective index.

Btw, if you are not familiar with array and essential data structure e.g. linked list, binary tree, and hash table, I suggest you to first go through

**Data Structures and Algorithms: Deep Dive Using Java**to build a foundation.##
3. __Code__

Now that we know how to solve this problem of missing numbers in **unsorted integer array**with duplicates, it's time to turn this solution into the code and working Java program./* * Java Program tofind missing numbers in an integer * array with duplicates. Array may contains more * than one duplicates. * * input: {1, 1, 2, 3, 5, 5, 7, 9, 9, 9}; * output: 4, 6, 8 */ public class Hello { public static void main(String[] args) { // given input int[] input = { 1, 1, 2, 3, 5, 5, 7, 9, 9, 9 }; // let's create another array with same length // by default all index will contain zero // default value for int variable int[] register = new int[input.length]; // now let's iterate over given array to // mark all present numbers in our register // array for (int i : input) { register[i] = 1; } // now, let's print all the absentees System.out.println("missing numbers in given array"); for (int i = 1; i < register.length; i++) { if (register[i] == 0) { System.out.println(i); } } } }

Output missing numbers in given array 4 6 8

This is the simplest Java program to solve this problem. You can see that

**we have hardcoded the input array**but you can also modify the program to get input from the user by using Scanner class as shown in this example.The code is exactly same as a solution, we created another array by copying length from original array and used it mark numbers which are present.

Since array indices are also integer and they are in the range of input values we can leverage them to use both as data and metadata. Had the array contains a number which is not in the range of 1 to N-1 then we couldn't have used an array. If you want to know more about array data structure, you can also see

**Algorithms and Data Structures - Part 1 and 2**courses on Pluralsight.Here is the summary of algorithm and code in a slide for better understanding:

##
4. __Analysis__

Now, the time is to analyze our solution to find the CPU and Memory complexity using Big O notation. If you look at the code then you will find that we are creating another array with the same size which means it has memory or **space complexity of O(n)**.This means if the array is too big like contains all the numbers in the integer range then we would a lot more memory which may not be available and our program could throw OutOfMemoryError in Java. This is even more possible because array needs a contiguous chunk of memory.

So, if we can remove the additional array which is not really holding anything and find a way to just store missing number which is quite less than the all the number that we can improve this solution, something for you guys to think.

For

**time complexity**, you can see that we iterate through the whole array to mark all present number and then iterate again to another array of the same length to find absentees. This means time complexity of this solution is O(n) + O(n) or O(2N) which is in Big O Notation still**O(n)**.We can further improve this solution if we

*find a way to print absentees as we iterate through the given array*. Again, something to think of you guys.That's all about this classic

**problem of finding missing numbers in a given integer array**. In this part, we have found a solution for finding multiple missing numbers in the unsorted array with duplicates. The time and space complexity of our solution is O(n).**Further Learning**Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

Cracking the Coding Interview: 189 Problems and Solutions

Other

**Coding Interview Questions**you may like- Print duplicate characters from String? (solution)
- Find duplicate characters in a String? (solution)
- Check if String is Palindrome? (solution)
- Find highest occurred character in a String? (solution)
- Check if a String contains only digits? (solution)
- Reverse String in Java using Iteration and Recursion? (solution)
- Count the number of vowels and consonants in a String? (solution)
- Find first non-repeated character from String? (solution)
- Count the occurrence of a given character in String? (solution)
- Convert numeric String to an int? (solution)
- Reverse words in a sentence without using a library method? (solution)
- Reverse a String in place in Java? (solution)

Thanks for reading this article so far. If you like this coding or algorithm interview question and my explanation then please share with your friends and colleagues. If you have any doubt or feedback then please drop a note.

**P.S. -**If you are preparing for Programming Job Interview and you need more such questions, can check the**Data Structures and Algorithms Bootcamp**by Jonathan Rasmusson course on Udemy.
## 16 comments :

If the array is not sorted, then we can sort it and then check the current and next number. If the gap is more than 1, then the current+1 number is missing. This will be done in 1 traversal and no extra space required, no? Only downside I see is sorting is required once. Any suggestions?

Yes, that's a good idea and nice approach, but sorting will take around O(NLogN) time, let's say if we use quicksort or mergesort, which makes it little slower than what we have currently i.e. O(n) solution. But, yes, if you trade off space and do in place sorting, which you should if its too big, this solution is good

Hi,

int[] input = { 1, 2, 3, 5, 7, 9 };

For this I am getting error.

We can solve this problem with space complexity of O(1);

private static void printMissingNumbers(int[] array) {

for (int i = 0; i < array.length; i++) {

int value = Math.abs(array[i]);

if (array[value - 1] > 0) {

array[value - 1] = -array[value - 1];

}

}

for (int i = 0; i < array.length - 1; i++) {

if (array[i] > 0) {

System.out.println(i + 1);

}

}

}

the program is incorrect if we alter the given array length...so make it for any length

The "register" array shouldn't be with the length of the "input" array. Instead it should be with the length of the max. element inside input - in this case: 9.

"Register" "999999999999000909999999999999"

"Register""999999999999999999"

for (int i : input) { register[i] = 1; }

why are we using this?

for (int i : input) { register[i] = 1; }

why are we using this?

@Anonymous, to check whether a number is present or not. It's like a map where key is array index and value is the array value. For example, if 10 is present than register[10] will be 1 and if 10 is not present then it will be zero as default value.

i am also getting error(ArrayIndexOutOfBond) if i am changing the length of array.

Hello Farman, can you provide more details? what are you trying to do? May be just share the test case or past the error you are getting?

What if the array contains negative integers, this solution won't work then.

Yes Ashish, good point, for negative numbers this won't work, can you solve that problem?

please tell me the same program in C

## Post a Comment