Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient method to remove null values within an array.

I am curious what the most efficient method of removing null values in arrays is. Here is my current null(0) removal method.

public static int[] removeNull(int[] array){
        int j = 0;
        for( int i=0;  i<array.length;  i++ )
        {
            if (array[i] != 0)
                array[j++] = array[i];
        }
        int [] newArray = new int[j];
        System.arraycopy( array, 0, newArray, 0, j );
        return newArray;
}

What is this method performance? I was expecting it to be n.

like image 781
joshLor Avatar asked Jun 26 '26 02:06

joshLor


1 Answers

Yes, your method's time complexity is O(n) - your loop has n (the length of the array) iterations, and copying an array requires time proportional to the size of the copied array, which in this case is O(n) in the worst case.

And you can't do better than that (in terms of time complexity), since you have to iterate over the entire array in order to locate the elements that should be removed.

If your goal is to reduce code complexity (i.e. write the shortest amount of code), you can use an IntStream (requires Java 8 or later):

public static int[] removeNull(int[] array) {
    return Arrays.stream(array).filter(i -> i != 0).toArray();
}

As Andreas commented, this solution has the advantage of leaving the original array unchanged.

like image 149
Eran Avatar answered Jun 28 '26 15:06

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!