+1 vote
6k views
in Java Interview Question by
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?

2 Answers

+1 vote
by Expert (5.9k points)

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

I hope it will help you! 

0 votes
by
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
myArraylist.add(randomNumber);
}
// 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
missingNumbers.add(j);
}
// Print missingNumbers
System.out.println("Missing numbers is : " + missingNumbers);

}

}

 

This will help you out!

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated