LeetCode Problem - Link


Problem

Given an integer array 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 1:

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).



So far, this problem - Remove Element from Arrays 101 course had me scratching my head for a while. First, the wording of the problem was complicated to understand what was being asked (check out the comments section), coupled that with the weird return conditions that are in place made this a pretty annoying problem to solve.


Anyway, after a bit of trial and error and digging through the comments I understood what was being asked. The crux of the problem solving method I had learned while solving this was pretty valuable.


Using a simple counter

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function (nums, val) {
    // since we dont care about items that are equal to val
    // we'll maintain an index on where to place an item thats !=val
    let index = 0;
    for (var i = 0; i < nums.length; i++) {
        // if you find a match, assign the value to the current index
        // then increment the index, getting it ready for next element
        if (nums[i] != val) {
            nums[index] = nums[i]
            index += 1
        }
    }


    // this is what they want us to return, so
    return index
};