LeetCode – Remove Element (Java)

Given an array and a value, remove all instances of that value in place and return the new length. (Note: The order of elements can be changed. It doesn’t matter what you leave beyond the new length.)

Java Solution

This problem can be solve by using two indices.

public int removeElement(int[] A, int elem) {
    int i=0;
    int j=0;
 
    while(j < A.length){
        if(A[j] != elem){
            A[i] = A[j];
            i++; 
        }
 
        j++;
    }
 
    return i;
}

6 thoughts on “LeetCode – Remove Element (Java)”

  1. Easiest way as above solution is not giving result in all scenarios. In addition I have used JAVA 8 .

    public int removeElement(int[] nums, int val) {

    int[] result = Arrays.stream(nums)

    .filter(num -> num != val).toArray();
    int j=0;
    for(int i =0;i<result.length;i++){
    nums[j] = result[i];
    j++;
    }
    Arrays.stream(nums).forEach(System.out::println);
    System.out.println("len"+j);
    return j;

    }

  2. Love the solution. Very clean.
    I thought of using two indexes – and replacing the the removed value with the non-removed.
    This changes the order but the question says it’s ok:

    int removeInstancesInPlace(int[] arr, int value)
    {
    for (int i = 0, end = arr.length-1 ; i <= end;)
    {
    if (arr[i] != value)
    {
    i++;
    continue;
    }

    arr[i] = arr[end];
    end--;
    }

    return end;
    }


  3. class Solution {
    public:
    int removeElement(vector& nums, int val) {
    int lastIndex = 0;
    for(int i = 0; i < nums.size(); i++) {
    if(nums[i] != val) nums[lastIndex++] = nums[i];
    }
    return lastIndex;
    }
    };

  4. dude its not wrong logic is correct. I dont get your point why the array you provide is not consistent with this code since i pass all testcases on leetcode with this similar logic code

  5. public class Solution {

    public int removeElement(int[] nums, int val) {

    if(nums == null || nums.length == 0){

    return 0;

    }

    int i = 0, j = nums.length -1;

    while(i<= j){

    if (nums[i] == val){

    if(nums[j] ==val){

    j–;

    continue;

    }else{

    nums[i] = nums[j];

    j–;

    }

    }

    i++;

    }

    return i;

    }

    }

  6. This solution is incorrect. You cannot ensure all duplicates would be removed not using another array or a default value for these duplicate values. Consider using this method with the int [ ] {2, 7, 7, 4}. The logic will not remove any of the duplicates.

Leave a Comment