Algorithm Question: Remove Element
Leet Code has been one of my favorite landing spots for javascript algorithms. It challenges me to expand my problem-solving skills. One particular problem I had a hard time solving was the “Remove Element” question. There were so many ways of solving this problem, however, I had to figure out which one would be more efficient and effective. The problem at hand is given two arguments: an array of numbers (nums) and an integer labeled as Val remove all occurrences of the Val integer. Easier said than done, I came up with a few interesting solutions. However, most did not work in my favor.
My first approach to the problem I created an empty array, iterating through the numbers I would check if the particular element is not equal to the value or type of the number value add it to the empty array. Furthermore, iterating through all my numbers I would return the empty array.
Unfortunately, LeetCode rejected my logic, therefore leaving me to scour the internet for different strategies.
When I discovered The two-pointer method it opened up new possibilities and was immediately added to my arsenal. The two-pointer method consisted of setting a variable to zero and eventually returning it based on conditional and pointer1.
I was able to solve this stubborn algorithm with this strategy. Below is the pseudo-code version.
I started by creating a variable called pointer1 and set it to zero. I iterated through the integers and created a second variable called pointer2. The conditional was the same as the first strategy If the number does not equal to the value or type of Val set pointer equal to pointer1. Once the conditional has been cemented I would increment pointer1 so it can continue throughout the array. Just as before I would return whatever change has occurred. Below is a visual representation of the solution enjoy.