• + 0 comments

    Swift, Here is my idea. It is easy to understand, however it is too long

    func gemstones(arr: [String]) -> Int {
        
        var uniqueData = Set<String>()
        var result = 0
        guard let firstIndex = arr.first else { return result }
        firstIndex.map { uniqueData.insert(String($0))}
        for i in 1..<arr.count {
            var temp = Set<String>()
            arr[i].map {
                temp.insert(String($0))
            }
            
            print("uniqueData \(uniqueData) and temp is \(temp)")
            print("intersection \( uniqueData.intersection(temp))")
            var intersection =  uniqueData.intersection(temp)
            result = intersection.count
            print("result ", result)
            uniqueData = []
            uniqueData = intersection
        }
        return result
    }
    

    Then, I refactor the code using formIntersection. we don't need the unnecessary variables

    func gemstones(arr: [String]) -> Int {
        guard let first = arr.first else { return 0 }
        var commonCharacters = Set(first.map { String($0) })
        
        for string in arr.dropFirst() {
            commonCharacters.formIntersection(string.map { String($0) })
        }
        
        return commonCharacters.count
    }