Hey there! any question in your mind? Ask It Now!.

Popular Categories





ArrayList- find Missing number

+1 vote
1,471 views
asked in Java Interview Question by Roma
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
answered by Himanshu Expert (5,940 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
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
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!

Related Questions

–1 vote
0 answers 126 views
0 votes
0 answers 71 views
+6 votes
1 answer 332 views
+2 votes
1 answer 108 views
+4 votes
1 answer 94 views
+2 votes
1 answer 220 views
0 votes
0 answers 56 views
+1 vote
0 answers 59 views

Not a Member yet?

Ask to Folks Login

My Account
781 Folks are online
0 members and 781 guest online
Your feedback is highly appreciated