How to keep zero values in an array of duplicates?

I’m still struggling to get the right input for this code where I need to remove duplicates and return the result. I get everything right until this:

  • given array [100, 0, 3, 4, 4, 562, 100]

  • the answer should be [100, 0, 3, 4, 562]

  • but what I get is [100, 3, 4, 562] (So it removes the 0)

Is there any way I can just add to my code since I’m not allowed to use any built-in functions, ArrayList, List, Set etc, so just implementing my own solution and functions.

public static int[] removeDuplicates(int[] input) {
    int[] withoutDubs = new int[input.length];
    int pos = 0;
    for(Integer element: input) {
        if(!checkIfInArray(withoutDubs, element)) {
            withoutDubs[pos] = element;
            pos++;
        }
    }
    int[] result = new int[pos];
    for(int i = 0; i < pos; i++) {
        result[i] = withoutDubs[i];
    }
    return result;
}

public static boolean checkIfInArray(int[] input, int number) {
    if(input == null) {
        return false;
    }
    for(Integer num: input) {
        if(num == number) {
            return true;
        }
    }
    return false;
}

Answer

withoutDubs is filled with 0s by default when it is first instantiated.

Therefore checkIfInArray(withoutDubs, 0) returns true even if 0 appears only once in the array.

You can pass an index to checkIfInArray, so that it doesn’t search all the withoutDubs array. It should only check indices 0 to pos - 1.

public static boolean checkIfInArray(int[] input, int last, int number) {
    if(input == null) {
        return false;
    }
    for(int i = 0; i < last; i++) {
        if(input[i] == number) {
            return true;
        }
    }
    return false;
}

and change the method call from

checkIfInArray(withoutDubs, element)

to

checkIfInArray(withoutDubs, pos, element)