Remove Element from an Array (Java)

LeetCode – Remove Element

Given an array and a value, 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 in place with constant memory.

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

Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.


This problem is similar to another leetcode problem: Remove Duplicates from Sorted Array

To solve this problem, we also define two indexes: pre and cur. Both are initialized to 0

We start cur from 0 until it reaches to the end of the array, For each cur, we check whether nums[cur] equals to the specified value. 

It they are equal, we continue the scan. Otherwise,  we assign nums[cur] to nums[pre], then let pre increase by 1

At the end, pre is the length of the target array. 

The following is the java implementation for removing element from an array..