Remove Elements - Easy  Leetcode Solution using TypeScript

Remove Elements - Easy Leetcode Solution using TypeScript

Understanding the 'Remove Element' Problem

The 'Remove Element' problem asks us to remove all occurrences of a specific number, val, from an array of numbers, nums.

Problem Type- Easy

https://leetcode.com/problems/remove-element/description/

O(n) Solution

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

Let me break it down for you:

  1. I used two pointers, i and k, to keep track of the array's elements.

  2. I checked if the current number is not equal to val.

  3. If it's not equal, I moved that number to the k-th position in the array.

  4. Finally, I returned k, which is the length of the new array without the specified number.

    It was easier for me as this problem was similar to Remove Duplicates , which also uses Two Pointers approach.

    Comment if I have committed any mistake. Let's connect on my socials. I am always open for new opportunities , if I am free :P

    Linkedin| Twitter | ShowwCase