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)/2
where 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 !!