2 Ways to Remove Numbers from Integer Array in Java?

In the last article, I have showed you how to reverse an array in place in Java and now I have come back with another array based coding interview question. It's also one of the frequently asked coding questions, not as popular as the previous one but still has been asked lot of times. Let's see the problem statement first.

Problem: Given an array and a value, write a function to remove all instances of that value from the array in Java (in place) and return the new length, or simply print out the array before and after removing the number. The order of elements can be changed. It doesn't matter what you leave beyond the new length. For example, if the given array is {12, 122, 12, 13, 14, 23, 14}, and number to be removed is 12 then the result array should be {122, 13, 34, 23,14}, and the length of the new array is 5.



How to remove a value from array in Java

In this article, I am going to show you two ways to remove a number from an integer array in Java. Our first solution will use the LinkedList class of Java Collection framework and the second solution will do it without using collection framework, as per the algorithm described below.

Solution 1:
In this solution, I have used a LinkedList class to collect all non-matching elements. So, I scan through original array and keep adding elements which are not equal to target value into LinkedList. Once I have completed the scan, I have all the numbers without target value in LinkedList. Later I use the Apache Commons ArrayUtils class to convert this LinkedList into an array in Java. There you go, you have removed the target number from the array without a fuss.

The only problem with this approach is that you need an extra LinkedList to hold rest of values and you now have your code dependent on Apache commons library.


Solution 2:
The most straightforward way to remove a value from an array is to loop through the whole array, from the beginning to end. When the target value (number) is found, remove it and move all numbers behind it backward. The overall complexity of this algorithm is quadratic i.e. O(n^2) since we have to move O(n) numbers when a target number is removed.

2 ways to remove an element from array in Java


Java Program to remove an element from array

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Sample Program to show how to remove elements from array in Java.
 * In this program, we have used two ways, first by using LinkedList
 * class of Java Collection framework and second without using Collection framework. *
 * @author javinpaul
 */
public class RemoveNumberFromArray {

    public static void main(String args[]) {

        System.out.println("Test #1 : General case to remove number  22");
        int[] input = {42, 322, 22, 11, 22, 33, 16};
        System.out.println("input : " + Arrays.toString(input) + ", remove 22");
        int[] output = remove(input, 22); // removes number 22 from array
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #2 : Remove number from empty array");
        int[] empty = {}; //empty array
        output = remove(empty, 23);
        System.out.println("input : " + Arrays.toString(empty) + ", remove 23");
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #3 : Remove number from array, without target number");
        int[] withoutTarget = {1, 2, 3, 4, 5, 6}; //empty array
        output = remove(withoutTarget, 12);
        System.out.println("input : " + Arrays.toString(withoutTarget) + ", remove 12");
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #4 : Delete element from array with only target numbers");
        int[] allWithTarget = {1, 1, 1, 1, 1, 1, 1};
        output = remove(allWithTarget, 1);
        System.out.println("input : " + Arrays.toString(allWithTarget) + ", remove 1");
        System.out.println("output : " + Arrays.toString(output));
    }


    /*
     * Removing a number from integer array with the help of LinkedList class
     */
    public static int[] removeNumber(int[] input, int number) {
        List<Integer> result = new LinkedList<Integer>();
        for (int item : input) {
            if (item != number) {
                result.add(item);
            }
        }
        return ArrayUtils.toPrimitive(result.toArray(new Integer[]{}));
    }


    /*
     * Removing element from array without using Collection class
     */
    public static int[] remove(int[] numbers, int target) {
        int count = 0;
        
        // loop over array to count number of target values.
        // this required to calculate length of new array
        for (int number: numbers) {
            if (number == target) {
                count++;
            }
        }

        // if original array doesn't contain number to removed
        // return same array
        if (count == 0) {
            return numbers;
        }

        int[] result = new int[numbers.length - count];
        int index = 0;
        for (int value : numbers) {
            if (value != target) {
                result[index] = value;
                index++;
            }
        }
        numbers = null; // make original array eligible for GC 
        return result;
    }
}

Output:
Test #1 : General case to remove number  22
input : [42, 322, 22, 11, 22, 33, 16], remove 22
output : [42, 322, 11, 33, 16]

Test #2 :  Remove number from empty array
input : [], remove 23
output : []

Test #3 : Remove number from array, without target number
input : [1, 2, 3, 4, 5, 6], remove 12
output : [1, 2, 3, 4, 5, 6]

Test #4 : Delete element from array with only target numbers
input : [1, 1, 1, 1, 1, 1, 1], remove 1
output : []


From the output, it's clear that our solution is working as expected. When we tested with an array where we have multiple target numbers it worked fine. We have also tested our solution with an empty array, an array which doesn't contain the value to be removed and an array containing the only value to be removed. It worked fine in all these scenario. You can create JUnit tests to capture each of these conditions and let me know if you still found any bug or typo in the code.


That's all about how to remove numbers from an array in Java. You have now learned two ways to delete an element from an array in Java. Though we have seen the example of removing the number from a numeric array, the algorithm is generic and will work with all types of array. You just need to create separate methods to accept different types of array e.g. method to remove an element from a long array or float array or String array.

Other array based coding questions from Java Interviews:
  • How to find all pairs in array whose sum is equal to k (solution)
  • How to remove an element from an array in Java? (solution)
  • How to check if an array contains a particular value? (solution)
  • How to find the largest and smallest number in an array without sorting? (solution)
  • How to find duplicates from an unsorted array in Java? (solution)
  • How to find one missing number in  a sorted array? (solution)
  • How to remove duplicates from an array in Java? (solution)

Further Reading
150 Programming Questions and Solutions
Data Structure and Algorithm in Java


1 comment:

  1. Hi Javin,
    I guess It can be solved O(n).
    Please check below solution.

    -----------CODE----------------
    public class DeleteAnyElementFromArray {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Integer[] ar = {12,3,5,1,12,6,9,12,15,-8,-1,12,-6,-3,5,7};
    int len = ar.length;
    System.out.println(len);
    int keyToDel =12;
    int j =0; //keeping J to count the freq of the item to be deleted
    int i=0;
    for(;i<len;i++){//O(n)
    if(ar[i] != keyToDel){
    ar[i-j] = ar[i];//I'm keeping the running index in check by reducing
    } //the increment index by the freq of the item to be deleted
    else
    j++; //increment when the element is "item to be deleted"
    }
    for(int k = i-j+1;k<i;k++){//O(n)
    ar[k] =null; //this loop shall perform worst when all the elements are same and they all have to be deleted
    }
    for (int k =0 ;k<i-j;k++){ //printing till the
    System.out.print(ar[k]+",");
    }
    }

    }

    ReplyDelete