LeetCode Blind 75 in Swift: Solving the "Contains Duplicate" Problem

Problem: Contains Duplicate

The Contains Duplicate problem asks you to determine if a given array contains any duplicates. Your task is to return true if any value appears at least twice in the array, and false if every element is distinct.

Example:

Input: nums = [1, 2, 3, 1]
Output: true
Explanation: 1 appears twice in the array, so we return true.
        

Swift Solution

class Solution {
    func containsDuplicate(_ nums: [Int]) -> Bool {
        var numSet = Set()
        for num in nums {
            if numSet.contains(num) {
                return true
            }
            numSet.insert(num)
        }
        return false
    }
}

let solution = Solution()
let nums = [1, 2, 3, 1]
let result = solution.containsDuplicate(nums)
print(result) // Output: true
        

Explanation

This solution leverages a Set in Swift, which stores unique elements. By iterating through the array, we check if the current element already exists in the set. If it does, we return true. If the iteration completes without finding duplicates, we return false.

Comments

Popular posts from this blog

LeetCode Blind 75 in Swift: Solving the "Find Minimum in Rotated Sorted Array" Problem

LeetCode Blind 75 in Swift: Solving the "3Sum" Problem

LeetCode Blind 75 in Swift: Solving the "Product of Array Except Self" Problem