Removing an Element
Hey guys, I hope you all had a great day and our week was off to a great start! For today’s algorithm problem, I’m going to write a function that takes in an array and a value and returns the same array with the value taken out of the array. Here are a couple of examples:
Input: nums = [3,2,2,3], val = 3
Output: [2,2]Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: [0,1,3,0,4]
So when I started out solving this problem, I thought of having two pointers run through the array and having a counter incremented each time an entry matched the inputted value. I later realized that having a counter isn’t really necessary because the output should be a smaller array, not the number of elements that match the value. So I scrapped that approach and started by iterating through the array and adding a condition for if the entry matched the inputted value. The condition was that the identical entry would be taken out of the array by using the .splice() built-in function as well as making sure that the iterator, i, doesn’t get incremented. I understand that reading it might be a bit confusing, so here’s the solution in terms of JavaScript code:
var removeElement = function(nums, val) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === val) {
nums.splice(i, 1);
i--;
}
}
return nums.length;
};
It’s funny, isn’t it? When you understand code better than English, or maybe it’s just my explanation is just really bad, either way, there’s the solution!
Anyways, if you guys learned something interesting or think the solution is pretty cool, click the clap button! If you have any better ways to solve it, feel free to leave a reply or contact me, thanks!