Saturday, April 18, 2020

Find Missing Number From Series/Array in Java

In this Java puzzle, you have a series of numbers start (e.g. 1….N) and exactly one number in this series is missing. You have to write a java program to find missing number from series.

Solution to find mising number

Surprisingly, solution of this puzzle is very simple only if you know it already.
  1. Calculate A = n (n+1)/2 where n is largest number in series 1…N.
  2. Calculate B = Sum of all numbers in given series
  3. Missing number = A – B
Let’s a write the solution in code.
public class FindMissingNumber {
    public static void main(String[] args) {
        //10 is missing
        int[] numbers = {1,2,3,4,5,6,7,8,9, 11,12};
         
        int N = 12;
        int idealSum = (N * (N + 1)) / 2;
        int sum = calculateSum(numbers);
 
        int missingNumber = idealSum - sum;
        System.out.println(missingNumber);
    }
 
    private static int calculateSum(int[] numbers) {
        int sum = 0;
        for (int n : numbers) {
            sum += n;
        }
        return sum;
    }
}
 
Output:
 
10

Solution to find mising number – Java 8

Above code, though simple, can be reduced by many lines using new language features such as lambda in Java 8. Let’s see how?
import java.util.Arrays;
 
public class FindMissingNumber {
    public static void main(String[] args) {
        //10 is missing
        int[] numbers = {1,2,3,4,5,6,7,8,9, 11,12};
         
        int N = 12;
        int idealSum = (N * (N + 1)) / 2;
        int sum = Arrays.stream(numbers).sum();
 
        int missingNumber = idealSum - sum;
        System.out.println(missingNumber);
    }
}
 
Output:
 
10
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 missing number in array, in your next interview.
Happy Learning !!

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...