Search code examples
pythonarraysalgorithmloopsduplicates

List contains duplicate Python solution


Can someone tell me if they see any problems with my solution below. It works fine on lists with duplicates [1,2,2,3], but fails with examples with no duplicates: [1,2,3,4]

Thanks in advance!

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        i = 0
        dis = 0
        while i < len(nums):
            if nums[i] in nums:
                i+=1
            elif nums[i] not in nums:
                i+=1
                dis+=1

        if i == dis:
            return False
        else:
            return True

Solution

  • So from what i understood you want to return True is list contains duplicates and False when its not? This can be done simply by converting the list into set, which cannot contain duplicates. Converting the list into set will remove all duplicates so if the set is smaller than the list, the list contains duplicates

    class Solution(object):
       def containsDuplicate(self, nums):
          """
          :type nums: List[int]
          :rtype: bool
          """
          return not len(nums) == len(set(nums))