27. Remove Element - Easy

 Given an integer array of nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.


Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  •     Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k
Example:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100


Solution:
var removeElement = function(nums, val) {
    let index = 0;
    
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== val) {
            nums[index] = nums[i]
            index++;
        }
    }
 return index;
}


Thoughts:
Couldn't initially figure out the solution when trying to use the built-in JS filter method; however I was very close. The solution would work typically, but it failed because I was using filter() to create a new array instead of modifying nums directly. Reassigning nums = newNums does not modify the original nums passed into the function.

Here is my incorrect example below:
var removeElement = function(nums, val) {
    const newNums = nums.filter(x => x !== val);
    nums = newNums;
    return newNums.length;
}

I understand the two-pointer solution above is much better because we overwrite the value of the num and move the pointer. I understand the solution 7/10 but still need some practice as I didn't get it the first time.

Comments

Popular posts from this blog

28. Find the Index of the First Occurence in a String - Easy

121. Best Time to Buy and Sell Stock - Easy

58. Length of Last Word - Easy