LeetCode Blind 75: Contains Duplicate


Greetings, traveler!

When preparing for technical interviews, one of the most common warm-up problems you’ll encounter is “Contains Duplicate” from the LeetCode Blind 75. It’s simple, but it introduces an important concept that appears again and again: using sets to detect uniqueness efficiently.

Problem Overview

The task is straightforward:

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Input: nums = [1, 2, 3, 1]
Output: true

Here, the number 1 occurs twice, so the answer is true.

Input: nums = [1, 2, 3, 4]
Output: false

All numbers are unique, so the function returns false.

Step-by-Step Solution

A naive approach would be to compare every element with every other element — but that takes O(n²) time, which isn’t great even for medium-sized arrays.

Instead, we can use a Set, which stores only unique values. As we iterate through the array, we check if the number has already been seen. If it has, we immediately return true. Otherwise, we insert it into the set and move on.

Swift Implementation (Iterative Version)

func containsDuplicate(_ nums: [Int]) -> Bool {
    var seen = Set<Int>()
    
    for num in nums {
        if seen.contains(num) {
            return true
        }
        seen.insert(num)
    }
    
    return false
}
  • Time Complexity: O(n)
  • Space Complexity: O(n)

This solution is efficient and easy to understand. It scales well for large arrays.

A More Compact Version

If you prefer a one-liner, Swift’s expressive syntax allows you to solve it in a single statement:

func containsDuplicate(_ nums: [Int]) -> Bool {
   Set(nums).count != nums.count
}

Here, we simply compare the number of unique elements (using Set) with the total number of elements.
If they differ, it means there are duplicates.