top of page
Rocky Mountains
Search

LeetCode 27. Remove Element

  • Writer: Raf Y
    Raf Y
  • Jan 5, 2024
  • 1 min read

Here I will provide a solution to Leetcode question 27: Remove Element. Below is my solution (you can also view a link to my solution on Leetcode):



Explanation:


The "high level" explanation of my solution is that I am implemented a "findLastIndex" function that starts from nums.length-1 and works its way back until it finds an index where array[index] !== val. We then use this index to swap out the first instance of val and some other element at some index towards that back of the array that we don't care about.


Finally, at the bottom, we return nums.length - (hits - swaps). We need to keep track of the number of vals we have as the questions requires us to keep track of k - "Consider the number of elements in nums which are not equal to val be k". We need to keep track of the number of "hits" we have of val, but also the number of swaps to account for situations where val is at the end of the array or we don't need to perform any swaps - this can happen if val is already located towards (the beginning of) the end of the portion of the array that we don't care about. Finally - we subtract hit - swaps by nums.length to get k.


I did not time myself for this question - I went way above 30 minutes which is my benchmark for succeeding in these questions as this is the time they give you in interviews in FAANG companies!

 
 
  • LinkedIn
  • Calendly
  • GitHub
bottom of page