⚡ TL;DR
Solve Contains Duplicate in Swift with working code. Hash Set (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Contains Duplicate (#217 — Easy): 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.
Problem Statement
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.
Example:
Input: nums = [1,2,3,1]
Output: trueApproach: Hash Set (Optimal)
Time: O(n) | Space: O(n)
A hash set rejects duplicate insertions. In Python, comparing lengths of list vs set is the idiomatic one-liner.
func containsDuplicate(_ nums: [Int]) -> Bool {
var seen = Set<Int>()
for num in nums {
if !seen.insert(num).inserted { return true }
}
return false
}
print(containsDuplicate([1,2,3,1])) // true
print(containsDuplicate([1,2,3,4])) // falseKey Takeaways
- Start with the brute-force approach to understand the problem
- Hash Set (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Contains Duplicate in Python
- Contains Duplicate in Dart
- Contains Duplicate in Go
- Two Sum in Swift
- Remove Duplicates from Sorted Array in Swift
- Maximum Subarray in Swift
FAQ
What is the best approach to solve Contains Duplicate in Swift?
The recommended approach is Hash Set (Optimal), which runs in O(n) time with O(n) space. The full Swift implementation is shown above.
What is the time complexity of Contains Duplicate in Swift?
Using Hash Set (Optimal), the time complexity is O(n) and the space complexity is O(n).
Happy coding!
