Find out n numbers of missing elements from an array in java
replace the else
clause to be:
for(int j=numbers[i-1] + 1; j <= numbers[i] - 1; j++) {
System.out.println( "Missing number is " + ( j ) );
}
let's examine the case: {9 ,6 ,4 ,5 ,7 ,0 , 1}
after sorting it will be: {0, 1, 4, 5, 6, 7, 9}
now if i
is at index 2 it finds the difference between numbers[i]
and numbers[i-1]
to be not equal 1 (4 - 1 = 3), now you need ALL the numbers between 1 and 4 which are 2, 3 and thus you must loop from numbers[i-1]
to numbers[i]
(exclusive) in order to achieve this.
The complexity of this code is big O of N
(O(N))
, where N
is the biggest element in your array.
This code uses a HashSet
:
public static void main(String[] args) {
int[] numbers = {9, 6, 4, 5, 7, 0, 1};
Arrays.sort(numbers);
HashSet<Integer> set = new HashSet<>();
for (int i = numbers[0]; i < numbers[numbers.length - 1]; i++) {
set.add(i);
}
for (int i = 0; i < numbers.length; i++) {
set.remove(numbers[i]);
}
for (int x : set) {
System.out.print(x + " ");
}
}
will print:
2 3 8
Here is how it works:
1. Adds all numbers from the minimum number of the array to the maximum number of the array to the set.
2. Iterates through the array and removes every item of the array from the set.
3. Prints the remaining items in the set, which are all the missing items of the array.