Write a Java Program to Find missing Number in an Array

Write a Java Program to Find missing Number in an Array thumbnail
10K
By Dhiraj Ray 15 February, 2020

This program is about finding the missing number from an array of length N-1 containing elements from 1 to N in Java. The trick to find the missing number is using the mathematical formula of Sum of Series to find the sum of N numbers and then subtract it from the sum of all the numbers of any given array.

Program Description

Assume, you have a number N(e.g. 9) and an array containing numbers from 1 to N-1 (e.g 1 - 8), meaning there is any random number missing in tha array between 1 to 9. Now, you need to write a Java program to find that missing number from the array.

Below is the sample program:

package com.devglan;

import java.util.Arrays;

public class FindMissingNumber {

    public static int calculateSumOfNNumbers(int n){
        return (n * (n + 1))/2;
    }

    public static int calculateSum(int [] array){
        return Arrays.stream(array).sum();
    }

    public static void main(String [] args){
        int n = 9;
        int[] numbers = {1, 2, 4, 9, 7, 8, 5, 6};

        int nNumberSum = FindMissingNumber.calculateSumOfNNumbers(n);
        int sumOfArray = calculateSum(numbers);

        int missingNumber = nNumberSum - sumOfArray;
        System.out.println(String.format("The missing number is: %s", missingNumber));

    }
}

Explanation

The method calculateSumOfNNumbers() find the sum of any natural number. The method calculateSum() calculates the sum of any given array. It uses Java 8 Stream operation to perform the sum.

In the main method, first we calculated the sum of N natural number and then calculated the sum of all the numbers in the given array. The difference between these two summation will give the missing number.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.