thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

LeetCode #217: Contains Duplicate

β€’ 113 words β€’ 1 min β€’ updated

LeetCode #217: Contains Duplicate:

With Counter():

python
from collections import Counter

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len([x for x in Counter(nums).values() if x >= 2]) > 0

OR a small variant with any:

python
from collections import Counter

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return any(x >= 2 for x in Counter(nums).values())

OR:

python
from collections import Counter

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        if not nums:
            return False

        return Counter(nums).most_common()[0][1] >= 2

OR with set():

python
from collections import Counter

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        s = set()
        for num in nums:
            if num in s:
                return True
            s.add(num)
        return False