DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
duccanhole
duccanhole

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
-Detail: https://leetcode.com/problems/remove-element/
-My solution (javascript):

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

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

Top comments (2)

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

Collapse
 
coderduck profile image
duccanhole Author

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

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!