Find Missing Numbers in Array - Java

A method to find all missing numbers in an array within an inclusive range.

    int[] findMissingNumbers(int[] arr, int from, int to) {

        int[] count = new int[to-from+1];

        int numEmpty = count.length, k = 0;

for (int num : arr)

    if (num >= from && num <= to)

if (count[num-from]++ == 0)

    numEmpty--;

int[] missingNums = new int[numEmpty];

for (int i = 0; i < count.length; i++)

    if (count[i] == 0)

        missingNums[k++] = i+from;

return missingNums;

    }


I was trying to use this method as a small step in a random generation for a game I've been working on, and I noticed that most of the code I saw online uses several loops and requires many preconditions, such as the search range not starting or ending within the range of the values of the array, or notably, requiring the array to be presorted. The former can be avoided with a dozen or so more lines of if-else statements and breaks; however, this code above is less than half as long and does not require a presorted array. This does still require the bounds of the range to be in ascending order (i.e. from <= to); however, this can of course be resolved with a simple max-min assignment or throw statement before. The inclusivity of the range can easily be changed to exclude the "to" value just by removing the "+1" from the length of count and changing the inequality in the first if statement. Changing the inclusivity of "from" is less trivial (and would be better accomplished by simply changing the input value) but nonetheless can still be done. I am by no means positing that this is the best way to go about writing this method, but it certainly seems much better than the method(s) I am referring to. I came up with this solution based off the first step in a counting sort— another algorithm with seemingly poor solutions portrayed online. If you have an ideas for better solutions feel free to comment.

Comments