#217

Contains Duplicate

Easy
ArrayHash TableSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashSet allows us to track the elements we have seen so far, making it easy to check for duplicates in a single pass through the array.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty HashSet.
  2. 2Step 2: Loop through each element in the array.
  3. 3Step 3: For each element, check if it is already in the HashSet. If it is, return true.
  4. 4Step 4: If it is not in the HashSet, add it to the HashSet.
  5. 5Step 5: If the loop completes without finding duplicates, return false.
solution.py7 lines
1def containsDuplicate(nums):
2    seen = set()
3    for num in nums:
4        if num in seen:
5            return True
6        seen.add(num)
7    return False

Complexity note: The time complexity is O(n) because we only pass through the array once. The space complexity is O(n) due to the HashSet storing up to n elements in the worst case.

  • 1Using a HashSet allows for efficient duplicate checking.
  • 2Brute force is simple but not practical for large inputs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.