# My solution in Python

• ``````import collections
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
length = len(nums)
counter = collections.Counter(nums)

if length<3:
return counter.keys()

result = []

words = counter.most_common(3)

for i in range(0,min(3,len(counter))):
if words[i][-1]>length/3:
result.append(words[i][0])
return result``````

• That clearly violates the O(1) space requirement.

Also, if you're going down that route, there's no need for such lengthy complicated code, you could just do this:

``````def majorityElement(self, nums):
return [number
for number, count in collections.Counter(nums).most_common(2)
if count > len(nums)/3]
``````

But again, that's an invalid answer because of the linear amount of space used.

• Hi, StefanPochmann. Your familiarity with Python is really fantastic! I have seen it again besides the `,` last time :-) Could I know how long have you been using it? Or could you recommend some nice study material for it?

• Nothing "fantastic" here, I just turned the already given pieces into the obvious list comprehension :-). I've been using Python maybe 2-3 years, but I'm not sure. I started with The Quick Python Book but I probably learned more from just using it, for example also at the wonderful CheckIO, a programming challenges website purely for Python. I learned quite a lot by looking at solutions of others there, particularly those of user "veky".

• Hi, StefanPochmann. Thank you for your nice reply :-)

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