Skip to content

Instantly share code, notes, and snippets.

@davidinga
Last active December 22, 2021 07:41
Show Gist options
  • Save davidinga/d64752f7358f4838cdebd2231b587886 to your computer and use it in GitHub Desktop.
Save davidinga/d64752f7358f4838cdebd2231b587886 to your computer and use it in GitHub Desktop.
Merge accounts with the same email address.
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