10 July, 2019

Find the Missing Number in a list


In this article, we will see how to find the missing number from a list using java.  This is one of important common interview question asked in interview. You can see, how to find all missing numbers from a list. In this program we will use core java or the traditional way using for loop for finding the miss number from a list. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find one missing number using traditional core java style. 


The logic is very simple here, see the below.

  • At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number. 
  • Then , we need to calculate the sum of all those natural number.
  • Then we will subtract each element from the given list from sumOfNaturalNumbers.
  • Now, the at the last  the value inside sumOfNaturalNumbers is the missing number.



FindOneMissingNumber.java


package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
/**
 * This program finds the missing number from a list. This is only for one
 * missing number using core java before jdk 8.
 *
 * @author manoj.bardhan
 *
 */
public class FindOneMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(
Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));
int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));
for (int i = 0; i < numberList.size(); i++) {
/*
* Substract each elements from list from sumOfNaturalNumbers and
* the final value will be the missing.
*/
sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
}
int missingNumber = sumOfNaturalNumbers;
System.out.println("Missing Number is :: " + missingNumber);
}
// Find the sum of all natural numbers up to limitNumber.
private static int getSumUptoMax(int limitNumber) {
int sum = 0;
for (int i = 1; i <= limitNumber; i++) {
sum = sum + i;
}
return sum;
}
// Find the greatest value from the list
private static int findMax(ArrayList<Integer> numberList) {
int largest = 0;
for (int i = 0; i < numberList.size() - 1; i++) {
if (numberList.get(i) >= largest) {
largest = numberList.get(i);
}
}
return largest;
}
}


Output -

Missing Number is :: 12



No comments:

Post a Comment