Sunday, 13 January 2019

Java Program to Find the Missing Number in an Array

         This is one of the most common Java coding interview questions. In an interview, you may be given an integer array containing numbers from 1 to n, where each number is unique (no duplicates are allowed). You will be asked to write a Java program to find the missing number in the array.

Example

int[] numbers = {1, 3, 5, 4, 2, 8, 7};

Output:

Missing number: 6

MissingNumber.java

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);
         }

}

Output:--
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