Recently I had a similar (not quite the same) question in an interview, and I also heard from a friend who was asked exactly the same question in an interview. So, here is the answer to the OP question and a few more options that could potentially be requested. An example of the answers is given in Java because it stated that:
Preferred is a Java solution.
Solution 1:
Array of numbers from 1 to 100 (both inclusive) ... Numbers are randomly added to the array, but in the array
there is one random empty slot,
public static int findMissing1(int [] arr){ int sum = 0; for(int n : arr){ sum += n; } return (100*(100+1)/2) - sum; }
Explanation: This solution (like many other solutions posted here) is based on the Triangular number formula, which gives us the sum of all natural numbers from 1 to n (in this case, n is 100). Now that we know the amount, which should be from 1 to 100, we just need to subtract the actual amount of existing numbers in the given array.
Solution 2:
Array of numbers from 1 to n (this means that the maximum number is unknown)
public static int findMissing2(int [] arr){ int sum = 0, max = 0; for(int n : arr){ sum += n; if(n > max) max = n; } return (max*(max+1)/2) - sum; }
Explanation: In this solution, since the maximum number is not specified, we need to find it. After finding the maximum number - the logic is the same.
Solution 3:
Array of numbers from 1 to n (the maximum number is unknown), in the array
There are two random empty slots:
public static int [] findMissing3(int [] arr){ int sum = 0, max = 0, misSum; int [] misNums = {};//empty by default for(int n : arr){ sum += n; if(n > max) max = n; } misSum = (max*(max+1)/2) - sum;//Sum of two missing numbers for(int n = Math.min(misSum, max-1); n > 1; n--){ if(!contains(n, arr))misNums = new int[]{n, misSum-n}; } return misNums; } private static boolean contains(int num, int [] arr){ for(int n : arr){ if(n == num)return true; } return false; }
Explanation: In this solution, the maximum number is not specified (as in the previous one), but two numbers may also be missing, not one. So, first we find the sum of the missing numbers - with the same logic as before. The second detection of a smaller number between the missing amount and the last (possibly) missing number - to reduce unnecessary search. Third, since Java Array (and not a collection) does not have methods like indexOf or contains , I added a small reuse method for this logic. Fourth, when the first missing number is found, the second is a subtraction from the missing amount. If only one number is missing, then the second number in the array will be zero.
Note
If you need examples from other languages or other interesting variations of this question , you can check out my Github repository for Questions and Answers Interviews .