A commonly asked puzzle at Java interviews is – finding the missing number from a series or array of numbers. This puzzle has been asked in an interview conducted on Amazon.com.
1. Problem
In this Java puzzle, w have a series of numbers start (e.g. 1….N), and exactly one number in this series is missing. We have to write a Java program to find the missing number from the series.
For example, in the following series, the number 10 is missing.
Series: 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12
Missing Number: 10
2. Solution
Surprisingly, the solution to this puzzle is very simple only if we know it already.
- Calculate
A = n (n+1)/2where n is the largest number in series 1…N. - Calculate B = Sum of all numbers in the given series
- Missing number = A – B
Let’s write the solution in code.
import java.util.Arrays;
public class FindMissingNumberFromSeries {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12};
int N = numbers[numbers.length-1]; //The last element in the array
int expectedSum = (N * (N + 1)) / 2;
int actualSum = Arrays.stream(numbers).sum();
int missingNumber = expectedSum - actualSum;
System.out.println(missingNumber);
}
}
Puzzles like these are simple to solve, but it is always useful to know the solution before it is asked in any interview. So be ready to find the missing numbers in the array, in your next interview.
Happy Learning !!
it’s better to replace add with xor, never overflow
Right! Was my first thought when I tried to do it myself. It will take constant space. To get XOR for given range next solution can be used
https://www.geeksforgeeks.org/find-xor-of-numbers-from-the-range-l-r/
But i just iterate full list and it doesn’t affect existing complexitty O(n), here is the code:
List nums = List.of(5, 10, 6, 4, 1, 3, 9, 8, 2);
int xorForFullList = 0;
for (int i = 0; i < nums.size() + 1; i++) {
xorForFullList ^= i + 1;
}
int xorForGivenList = 0;
for (Integer num : nums) {
xorForGivenList ^= num;
}
int missingNum = xorForFullList ^ xorForGivenList;
System.out.println("missingNum=" + missingNum);
how to find multiple numbers missing in a sequence using java 8 streams?
why he is taken N=12 only
It is the largest number in series.
How is it coded if there are more numbers like 1 to 200?