# ArrayList- find Missing number

+1 vote
1,968 views asked
There was a question in my interview,  please find Missing number from arraylist where numbers are adding randomly.  Can you please tell me the answer with a code example?

+1 vote

Its very simple , first of all iterate the array and  get the sum of all number , As we know sum of natural numbers from 1 to n we can write as n*(n+1)/2. Now we have to subtract the sum of the array from [n*(n+1)/2] .

Here we get the missing number .

See the code example :

int sum = 0; int index = -1;

for (int j = 0; j < array.length; j++) {

if (arr[j] == 0) {

index = i;

} else {

sum += arr[j];

}

}

int total = (array.length + 1) * array.length / 2;

System.out.println("This number is missing...: " + (total - sum) + " at index " + index); answered by Elena
Checked this out to find Missing number from arraylist:

import java.util.ArrayList;
import java.util.Random;
/*
* Code for missing number from arrayList whereNumbers added randomly

public class MissingNumber {

public static void main(String[] args) {

// declare an ArrayList to hold the random numbers
ArrayList<Integer> myArraylist = new ArrayList<>();
// declare an ArrayList to hold the missing numbers
ArrayList<Integer> missingNumbers = new ArrayList<>();

int maxRanNumb = 10;// random numbers will be 0-9
int size = 20; // size of myArrayList

for (int j = 0; j < size; j++) {
// Generate random numbers
Random rand = new Random();
int randomNumber = rand.nextInt(maxRanNumb);
// Put random numbers into myArrayList
}
// Print myArrayList
System.out.println("Contents of myArraylist: " + myArraylist);

// Search missing number
for (int j = 0; j < maxRanNumb; j++)
if (!myArraylist.contains(j)) {
// Put missing numbers into missingNumbers
}
// Print missingNumbers
System.out.println("Missing numbers is : " + missingNumbers);

}

}

## Related Questions

–1 vote    