LeetCode Problem Solution #27: Remove Element

Mariah Morales
2 min readJun 24, 2022

Another leetcode problem! I’m trying to get accustomed to doing them everyday but having a little mobile 8-month-old has not been an easy adjustment. Nevertheless, let’s move onto the problem.

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

This is the beginning of our function. our function takes in a nums array and val which represents an integer.

At this point, it’s pretty standard that if given an array, we are definitely going to be iterating over it! Let’s code that out. I personally like for loops!

Now comes the most important part. We need to remove all occurrences of val in nums in-place. We can simple start with creating an if statement that will check if a num in our nums array is equal to our val integer.

Now we need to remove all occurrences of val in nums in-place. We will be using the splice method to take care of this and then increment down our index.

Finally, we return our nums.length

--

--