Procedure to approach this question would be:
Sort the elements in the array using any sorting algorithm of
choice depending on the complexity you want
Loop through the sorted Array
Check to see if the arr[index + 1] - arr[index] != 1, then
It indicates, a number is missing
Get the difference between these indexes
Create a temporary list to store missing numbers
Using a for-loop, from 1 up to the difference range, add
1 to the arr[index] and store in missingNumbers list
Now loop through missingNumbers list, to get all your missing numbers
An implementation using Java which caters for both (negative and positive) numbers
import java.util.LinkedList;
import java.util.List;
public class missingElement {
public static void main(String[] args) {
int values[] = {17, 1, -4, 2, 3, 4, 6, 7, 9, 8, 10 ,15,23};
int[] arrSorted = sortValues(values);
//pass sorted Array to get Missing Numbers
List<Integer> results = getMissingNumbers(arrSorted);
for (int value : results) {
System.out.println(value);
}
}
public static int[] sortValues(int[] arr) {
// sort in asc first (any sort algo will do depending on the complexity you want
// going with bubble sort
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static List<Integer> getMissingNumbers(int[] arr) {
List<Integer> missingNumbers = new LinkedList<>();
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < arr[i + 1]) {
if (arr[i + 1] - arr[i] != 1) {
int rangeLeft = arr[i + 1] - arr[i];
for(int k=1; k < rangeLeft; k++) {
missingNumbers.add(arr[i] + k);
}
}
}
}
return missingNumbers;
}
}
