You can use a set and every time you try to insert an element it fails it means it is a duplicate. You would need also to make sure you don't keep duplicate elements on the result:
func findDuplicates (array: [Int]) {
var set: Set<Int> = []
for i in array {
if !set.insert(i).inserted {
print("duplicate element:", i)
}
}
}
findDuplicates(array: [1,2,3,4,5,6,5,6,7,9])
This will print:
duplicate element: 5
duplicate element: 6
If you would like to return all duplicate elements of a collection you can simply use filter:
func getDuplicates(in array: [Int]) -> [Int] {
var set: Set<Int> = []
var filtered: Set<Int> = []
return array.filter { !set.insert($0).inserted && filtered.insert($0).inserted }
}
getDuplicates(in: [1,2,3,4,5,6,5,6,7,9]) // [5, 6]
extension RangeReplaceableCollection where Element: Hashable {
var duplicates: Self {
var set: Set<Element> = []
var filtered: Set<Element> = []
return filter { !set.insert($0).inserted && filtered.insert($0).inserted }
}
}
let numbers = [1,2,3,4,5,6,5,6,7,9]
numbers.duplicates // [5, 6]
let string = "1234565679"
string.duplicates // "56"