Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Remove Element

Sharing is caring!

Problem Statement
Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Solution

public class RemoveElement {
    public static int removeElement(int[] nums, int val) {
        int newLen = nums.length;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                newLen--;
            }
        }

        int lastIndex = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val && lastIndex == -1) {
                lastIndex = i;
            } else if (nums[i] != val && lastIndex >= 0) {
                nums[lastIndex] = nums[i];
                lastIndex++;
            }
        }

        return newLen;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0, 1, 2, 2, 3, 0, 4, 2};
        int len = removeElement(nums, 2);

        for (int i = 0; i < len; i++) {
            System.out.print(nums[i] + " ");
        }
    }
}