Monday, September 25, 2023

How to Find Multiple Missing Integers in Given Array of Numbers with Duplicates in Java?

Hello guys, 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 problems 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 candidates and further test their ability to adapt to frequent changes, which is key to surviving in the ever-changing software development world.

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 kind of make those problems a bit easier.

That makes the problem somewhat easy but what do you do if the 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.

Btw, it's also helpful to know the essential coding patterns  like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve many frequently asked coding problems. 

Many programmers miss that part and instead went to prepare for 100+ Leetcode problems which often require more time and still they struggle to solve a new coding problem which they have never seen before.

To avoid this mistake I suggest you go through Grokking the Coding Interview: Patterns for Coding Questions an interactive and useful course on Educative and learn those essential 15+ coding patterns for interviews.






1. Problem - How to Find more than missing numbers in Array with Duplicates?

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 the 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. The solution to finding missing numbers from the given array

When you see the question is to find the missing number in an array, you might think about our earlier solution of calculating the sum of all the numbers and deducting it from the 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 the names of all students, he goes through the list and marks 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 like a linked list, binary tree, and hash table, I suggest you first go through Data Structures and Algorithms: Deep Dive Using Java to build a foundation.

Find Multiple Missing Integers in Given Array of Numbers with Duplicates in Java?



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 to find 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 the same as a solution, we created another array by copying length from the original array and used it mark numbers that are present.

Since array indices are also an 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 the array data structure, you can also see Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight.

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




4. Analysis and Explanation of Logic

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 numbers which is quite less than all the numbers 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 numbers and then iterate again to another array of the same length to find absentees. This means the 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).


Other Coding Interview Questions you may like
  • Print duplicate characters from String? (solution)
  • Find duplicate characters in a String? (solution)
  • 50+ Data Structure and Algorithms Interview Questions (list)
  • Check if String is Palindrome? (solution)
  • 20+ array-based coding problems from interviews (questions)
  • 10 free Data Structure Courses for Beginners (Free DSA courses)
  • Find the 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 the first non-repeated character from String? (solution)
  • Count the occurrence of a given character in String? (solution)
  • My favorite free course to learn Data Structure and Algorithms (courses)
  • 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 it with your friends and colleagues. If you have any doubts or feedback then please drop a note.

P.S. - If you are preparing for Programming Job Interview and you need more such questions, you can check the Data Structures and Algorithms Bootcamp by Jonathan Rasmusson course on  Udemy. This is a great course to build and level up your Data Structure and Algorithms skills to become a better programmer.

And lastly one question for you? What is the time and space complexity of this solution? how can you improve this solution by using a data structure? 

18 comments:

  1. 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?

    ReplyDelete
  2. 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

    ReplyDelete
  3. Hi,

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

    For this I am getting error.

    ReplyDelete
  4. 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);
    }
    }
    }

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

    ReplyDelete
  6. 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.

    ReplyDelete
  7. "Register" "999999999999000909999999999999"

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

    why are we using this?

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

    why are we using this?

    ReplyDelete
  10. @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.

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

    ReplyDelete
  12. 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?

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

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

    ReplyDelete
  15. please tell me the same program in C

    ReplyDelete
  16. HI Javin paul,

    ArrayIndexOutOfBond isssue will come if any alteration to array. Because while iterating input you are setting 1 to register array, but what if register[i] value larger than length of register array.

    Simple Register array should not be length of main array.

    ex: int[] input = { 1, 1, 2, 3, 7, 9, 9, 9 };
    System.out.println(input.length);
    int[] register = new int[input.length];
    System.out.println(register.length);
    for (int i : input) {
    register[i] = 1;
    }

    output: 8
    8
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at MIssingAndRepeatNumberInArray.main(MIssingAndRepeatNumberInArray.java:14)

    Reason: my register array length only 8 but input array value is 9

    Solution: static only - can use map instead of register for 100% proper solution
    int[] input = { 1, 1, 2, 3, 7, 9, 9, 9 };
    System.out.println(input.length);
    int[] register = new int[100];
    System.out.println(register.length);
    for (int i : input) {
    register[i] = 1;
    }
    System.out.println("missing numbers in given array");
    for (int i = 1; i < input.length; i++) {
    if (register[i] == 0) {
    System.out.println(i);
    }
    }

    ReplyDelete
  17. int[] array = { 1, 2, 3, 5, 7, 10,9,15 };


    for(int i=0 ; iarray[j])
    {
    temp=array[i];
    array[i]=array[j];
    array[j]=temp;

    }
    }

    }

    int[] holder=new int[array[array.length-1]];
    for(int i : array)
    {
    holder[i-1]=1;
    }

    for(int i=0 ; i< holder.length;i++)
    {
    if(holder[i]==0)
    {
    System.out.println(i+1);
    }
    }

    ReplyDelete