Question

Example 1

  • Input: nums = [1,2,3,1]
  • Output: true
  • Explanation: The element 1 occurs at the indices 0 and 3.

Restate the problem

  • Given an integer array nums
  • Return True if any value appears at least twice, otherwise return False.

Edge Case

  • [], return False
  • len(nums) < 2, return False

MethodApproachTime ComplexitySpace Complexity
Method 1 ⭐HashmapO(n)O(n)
Method 2SortO()O(1)

Method 1: HashSet

Approach

  • Initial an empty set seen(only stores unique values)
  • Scan the nums
  • If num in seen, return True
    • Add num into set

Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Code

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

Method 2: Sort + Scan

Approach

  • Sort nums
  • Scan sorted nums, start from 1
    • If the current number equals the previous number, return True

Complexity

  • Time Complexity: O()
    • Sorting:
  • Space Complexity: O(1)

Code

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] == nums[i - 1]:
                return True
        
        return False

History

  • Feb-27-2026 Solved
  • Jan-15-2026 Solved