How to find duplicates in Array?

[Question] In a given array return true if array have duplicate elements . For example 1 :[1,2,3,1] = True example 1 :[1,2,3,] = False

class Solution {
    // Time Complexity o(n)
    // Space Complexity o(1) 
    func containsDuplicate(_ nums: [Int]) -> Bool {
        var dict: [Int: Int] = [:]
        for value in nums {
            if dict[value] == nil {
                dict[value] = 0
            } else {
                return true
            }
        }
        return false
    }
}

So here we have used Dictionary which is Hashable which contains only unique keys hence we can find duplicates elements in swift.

Leave a Comment

Your email address will not be published. Required fields are marked *