DEV Community

Cover image for Remove Element - LeetCode
zuzexx
zuzexx

Posted on

Remove Element - LeetCode

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

The goal of this challenge is to remove all occurrences of a specified value in an integer array, without creating a new array. The relative order of the elements may be changed. This technique is known as "in-place" modification.

Here's a JavaScript solution to this problem:

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

Let's break down the code and understand how it works:

  1. We declare a variable i and initialize it to 0. This variable will keep track of the position in the array where the next non-matching element should be placed.

  2. We have a for loop that starts at index 0 and goes up to the length of the nums array. The variable j will keep track of the current index we're checking in the nums array.

  3. In the loop, we check if the current element in the nums array, nums[j], is equal to the specified value val.

  4. If the current element does not match the specified value, we copy it over to the current position in the array being tracked by i. This effectively removes the occurrence of the specified value.

  5. Finally, we increment i by 1, ready to copy over the next non-matching element.

  6. When the loop ends, the i variable will hold the length of the new array after all the occurrences of val have been removed.

And that's it! With this simple code, we can remove all occurrences of a specified value from an array in-place, changing the relative order of the elements in the process if necessary.

Top comments (0)