# Python 2-liner, O(N)

• ``````from collections import OrderedDict
class Solution(object):
def removeDuplicates(self, nums):

nums[:] =  OrderedDict.fromkeys(nums).keys()
return len(nums)
``````

• hi ahendy,

nums[:] = OrderedDict.fromkeys(nums).keys()

why directly use nums = ... does not work? thanks in advance

• Using nums[:] will not allocate new memory, instead will change the values already used by nums. rather than just reassigning the name nums to the newly created list.
Here is a quick test you can do to test this in python interpreter:

``````a = [1,2,3,4,5]
b = a #
>> [1,2,3,4,5]
a[:] = [1, 2, 3]
print b
>> [1, 2, 3]
``````

As you can see b = a means set b to point to the memory location of a, then using [:] (slice of entire list) it modifies what b points to.

Using OrderedDict is a workaround to not having set() implemented if you also are curious of that.

• ``````class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = list(set(nums))
res = sorted(res)

print res

return len(res)
``````

``````[1,2,2,3,3]
``````

``````[1, 2, 3]
``````

``````[1,2,2]
``````

Any idea what's wrong?

• This post is deleted!

• @yuan31 a workaround would be to use an ordered dict as I did in my answer.

• @ahendy

``````class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = list(set(nums))
res = sorted(res)

nums[:] = res
return len(nums)
``````

the above code worked. What's the difference between nums[:] = res and nums = res?

• @yuan31 I have a pretty good explanation of the difference of 'a[:] =' and 'a =' above. let me know if it makes sense.

• @yuan31 It seems that you allocate an extra space for the array

• No need for `.keys()`, you can remove that.

• @StefanPochmann very interesting

• @StefanPochmann Thanks a lot!

• @ahendy Nice solution. I am curious why len(sorted(Counter(nums))) doesn't get accepted. Which if I am not mistaken outputs the same thing .

• i think apart from checking the return value of the function, they are also checking the value of num after the function gets excuted

• Ordered dict works because it maintatins order of the original list,but the set does not

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.