[LeetCode] Top Interview 150 Problems Solving # 27 Remove Element
Understanding the Problem
There is a list of nums as nums
and a single integer as val
. If the given list has the value val
, it should be taken away from the list. The instruction was clear with the finishing words that I need to return k
, which is the count of the values that are not equal to val
. As far as I understood the question, the input and output should look something like this.
# input
nums = [1, 2, 3]
val = 3
# output
nums = [1, 2]
k = 2
Approach
I was having a hard time figuring out what the output should look like, because when I ran the test case the input and output were not the same as what I thought it should be.
# input
nums = [3,2,2,3]
val = 3
# expected
[2,2]
Wait, the instruction was saying that I should return k
and this is an integer, not a list. But why is it expecting a list?
At least I understood that intput nums
is to be fixed in-place by removing all val
in the list and thought k
is not the key to complete the problem.
Solution
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
I went directly removing the val
in the nums
with the remove() method with while
loop until the val
is completely removed from the list. It took me somehow a while to solve this question as I was stuck with the logic without while but I solved it anyway.
Reflection
In LeetCode web other people solved the question by returning k
, or returning other values. I do not know what the logic in the back is but this instruction was unclear and confusing. Yet, the human error can happen, and solving this kind of problem is somewhat fun though.