Last active
December 22, 2021 07:41
-
-
Save davidinga/d64752f7358f4838cdebd2231b587886 to your computer and use it in GitHub Desktop.
Merge accounts with the same email address.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func accountsMerge(_ accounts: [[String]]) -> [[String]] { | |
var accounts: [Account] = accounts.map { | |
var account = Account(name: $0.first!) | |
for i in 1 ..< $0.count { | |
account.emails.insert($0[i]) | |
} | |
return account | |
} | |
var i = 0 | |
while i < accounts.count { | |
for j in i + 1 ..< accounts.count { | |
let hasDuplicateEmail = !accounts[i].emails.isDisjoint(with: accounts[j].emails) | |
if !hasDuplicateEmail { continue } | |
accounts[i].emails.formUnion(accounts[j].emails) | |
accounts.remove(at: j) | |
i -= 1 | |
break | |
} | |
i += 1 | |
} | |
return accounts.map { | |
var account: [String] = [] | |
account.append($0.name) | |
for email in $0.emails.sorted() { | |
account.append(email) | |
} | |
return account | |
} | |
} | |
struct Account { | |
var name: String | |
var emails: Set<String> = [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment