DEV Community


Posted on

code every day with me

--DAY 7--
Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
-Problem: Remove Element
-My solution (javascript):

var removeElement = function(nums, val) {
    let i=0;
    for(let j=0;j<nums.length;j++)
    return i;
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Discussion (2)

grendel profile image
grendel • Edited on

I think you should change return i to return nums.splice(--i).length since if you run this function over the same array multiple times, it can eventually start putting formerly-removed elements back into the array (or work on an array whose "real length" should be 0 long ago) since subsequent iterations will traverse all the way to original index N, when the length should be N-i each time. In a language that can't resize an array, like C for example, this would be accomplished by placing a null byte at index i to stop traversal at the new length on subsequent runs.

Edit: it just occurred to me that in C, null-termination is a thing for character arrays (strings) and other such potentially variable-length arrays, and not for every array, like ints. It only would matter if code that iterates over the array will check for and stop on a null byte. Otherwise, returning the number of erased elements should be enough, since it should be calling code's responsibility to subtract that from wherever the array's length is recorded.

coderduck profile image
duccanhole Author

I only code by js, so i dont know that. Thank you!