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;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • skylogic

    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

  • lala

    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;

    }

    }

  • NEWLIGHT

    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.