Sunday, 13 January 2019

Java Program to find the Missing Number in an Array

        This is one of the basic java coding interview questions. In interview, they will give an integer array from 1 to n and each number of array can not be duplicate. They will ask to write the java code to find the missing number of an array.

For Example:-

int[] numbers = {1,3,5,4,2,8,7}; 
Missing number is 6.,

package com.sample;

public class MissingNumber {
        public static void main(String[] args) {
                  int[] numbers = {1,4,2,5,3,6,7,9}; 
                  int totalNumbers = numbers.length + 1;
                  System.out.println("Total numbers - "+totalNumbers);
                    // first to calculate the sum of total numbers
                   int sumOfTotalNumbers = (totalNumbers * (totalNumbers + 1)) / 2;
                   // find the sum of given array. 
                   int sumOfArrayNumbers = 0;
                   for (int i=0; i<numbers.length; i++) {
                            sumOfArrayNumbers = sumOfArrayNumbers + numbers[i];
                   int missingNumber = sumOfTotalNumbers - sumOfArrayNumbers;
                   System.out.println("Missing number - "+missingNumber);


Total numbers - 9
Missing number - 8

Thank you for visiting blog.

Some other related posts:-
1) Java Program to check the given number is a palindrome or not
2) Write a Java program to print the Floyd's triangle
3) Java Program for Bubble Sort in Ascending and Descending order
4) Java Program to Reverse a Linked List using Recursion and Loops
5) Java Program to Count Occurrence of Word in a Sentence
6) How to Remove duplicates from ArrayList in Java
7) Java program to print the first n prime numbers

No comments:

Post a comment