I can't test code now on the web you linked. But I think you can imagine the testcase as follow (I'm just guessing here, so this answer might not work properly):
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = list(set(nums))
return len(nums)
nums = [1, 1, 2]
solver = Solution()
length = solver.removeDuplicates(nums)
print(nums[:length])
So, by watching the test case, you can see that you actually get [1, 1]
, since you are not modifying the list, but you are creating a new local variable within the method scope. You could try doing something like this maybe:
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
while i < len(nums) - 1:
if nums[i] == nums[i+1]:
del nums[i]
else:
i += 1
return len(nums)
nums = [1, 1, 2, 2, 2, 3]
solver = Solution()
length = solver.removeDuplicates(nums)
print(nums[:length])
When they ask for an algorithm "in-place" you are not supposed to create new variables (or overwritte the old one with a new list), that's not O(1) extra memory, it's O(n), since you are creating a new copy.
EDIT A bit more explanation
What is happening with your code, is that you create a new local variable in a new memory space (In case you know about computers, you create it in the stack) therefore, inside your function you lose the reference to the pointer that gives you the outter nums variable (the original list). So the nums variable in the function (stack) is setted as a list created by iterating all different elements of the original list. Then, you really get a copy that meet all the requirements and is stored in the stack, but the old list stays the same. Then, when you exit your function, the stack variable is lost, so when you access to the num
variable, you will get the old one (the original).
To understand what's going on here, you can read this to learn about scopes, and this to learn about passing arguments to functions.