The question says:
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.
You'll also not want to create another array as the expected Space complexity is O(1).
Here's how I tackled it:
Store the length of the given array in a variable, nums_length
Declare a variable length_of_nums to 0. This would later act as the counter in our loop
Create a loop to run if length_of_nums is less than nums_length
Create a second loop to check if the length_of_nums(counter) element in the nums array is equal to the value given to check. if the condition for the loop is not met, increment the length_of_nums by 1
If the two elements are same, pop out the element in the array
decrement the nums_length by 1
Check if the nums_length is equal to the length_of_nums to break out of the inner loop. (This checks for edge cases)
return length_of_nums
Using this approach gives you the array in memory without duplicates so you can return the new length of the array.
Top comments (0)