Search code examples
javacontains

True if arr does not contain target


The goal is to return true if arr does not contain target and false otherwise:

public boolean arrayDoesNotContain(int[] arr, int target){
    for (int element : arr) {
        if (element != target) {
            return true;
        } 
    }
    return false;
    
}

I ran this and am getting assertion errors on my tests even though it fulfills the required task. Any tips or a second pair of eyes to help me see where this went wrong is appreciated.


Solution

  • It's difficult to pinpoint the issue without seeing the tests and the specific assertion errors you're receiving, but one thing to consider is that the current implementation will return true as soon as it finds an element in the array that is not equal to the target, without checking the rest of the elements.

    Try this and let me know if that works

    public boolean arrayDoesNotContain(int[] arr, int target){
        for (int element : arr) {
            if (element == target) {
                return false;
            } 
        }
        return true;
    }