Very simple java solution with explanation

  • 2

    The idea is to use insertion , we keep the index of where we want to insert the next element. As we go through the loop if we see a val that is != to val then we insert it to the insertIndex position. Since we dont care about whats after we can stop after one loop. So basically we are overwriting the beginning part of the array with valid numbers.

       public int removeElement(int[] nums, int val) {
        int n = nums.length;
        int insertIndex = 0;
        for(int i = 0; i < n ; i++){
            if(nums[i] != val){
                nums[insertIndex] = nums[i];
        return insertIndex;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.