Find missed number in an Array List (Java). Best interview solution - Boris
IT Blog
Boris IT Expert

# Easily solution to find a missed number in an array list in Java.

Boris~November 6, 2020 /Uncategorized

How to find a missed number in an array list in Java? One of the most frequently asked questions on the technical interview. There are several moments you should keep in mind. First of all, with the formula (n) * (n + 1) / 2, we will find the sum of all natural numbers. After that, we should subtract each element of the array from the sum. As a result, we would get the element that has been missed.

## How to find the missed element in an Array List (Java)? Step-by-step implementation.

If you need a simple solution for this task, you have to follow the detailed instructions below:

• The main trick here is to find the sum of all natural numbers in an array list with the formula (n) * (n + 1) / 2. N here is the size of the array list;
``````//Getting the size of the array to use it in the formula
int size = array.length;

//Sum of natural numbers calculated by formula n*(n+1)/2
//Since we use array and one item is missed we need to add 1 in both cases
int result = (size + 1) * (size + 2) / 2;``````
• With the help of the loop, subtract each element from the sum;
``````//From total number with each iteration we minus each item of the array list
for (int i : array) {
result -= i;
}``````
• The number that you have after the looping is over. Is our result;

All steps schema:

Full code solution:

``````private void findMissedElement() {
//Creating new array of integers
int[] array = new int[]{1,5,4,2,6};

//Getting the size of the array to use it in the formula
int size = array.length;

//Sum of natural numbers calculated by formula n*(n+1)/2
//Since we use array and one item is missed we need to add 1 in both cases
int result = (size + 1) * (size + 2) / 2;

//From total number with each iteration we minus each item of the array list
for (int i : array) {
result -= i;
}

//The rest number is the result
Log.d("arrayList", "result-> " + result);
}``````

In this article, I show you the solution for two sum problem (Java0.

Full code and more examples in my facebook group.