Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Accounts Merge

Posted on June 18, 2019July 26, 2020 by braindenny

Accounts Merge



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #unionfind

Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

Example 1:

Input: 
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
Explanation: 
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.

Note:

  • The length of accounts will be in the range [1, 1000].
  • The length of accounts[i] will be in the range [1, 10].
  • The length of accounts[i][j] will be in the range [1, 30].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/accounts-merge
// Basic Ideas: union find
//
// Complexity: Time ?, Space ?
import "sort"

type UF struct {
    parent []int
}

func constructor(size int) UF {
    parent := make([]int, size)
    for i, _ := range parent {
        parent[i] = i
    }
    return UF{parent}
}

func (uf *UF) union(node1 int, node2 int) {
    parent1 := uf.find(node1)
    parent2 := uf.find(node2)
    // connect parent1 with parent2
    // TODO: rank
    uf.parent[parent2] = parent1
}

func (uf *UF) find(node int) int {
    res := node
    for uf.parent[res] != res {
        res = uf.parent[res]
        // TODO: path compression
    }
    return res
}

func accountsMerge(accounts [][]string) [][]string {
    uf := constructor(len(accounts))
    email_node := map[string]int{}

    // Build nodes
    for i, account := range accounts {
        for j:=1; j<len(account); j++ {
            email := account[j]
            v, ok := email_node[email]
            if ok {
                // Build connections
                uf.union(v, i)
            } else {
                email_node[email] = i
            }
        }
    }
    res := [][]string{}
    // Combine emails to its parent
    res_map := make([]map[string]bool, len(accounts))
    for i:=0; i<len(accounts); i++ {
        res_map[i] = map[string]bool{}
    }
    for i, account := range accounts {
        parent := uf.find(i)
        for j, email := range account {
            if j == 0 { continue }
            res_map[parent][email] = true
        }
    }

    // Get results
    for group, email_set := range res_map {
        if uf.parent[group] == group {
            name := accounts[uf.parent[group]][0]
            l := []string{}
            for k, _ := range email_set {
                l = append(l, k)
            }
            sort.Slice(l, func (i, j int) bool {
                return l[i] < l[j]
            })
            res = append(res, append([]string{name}, l...))
        }
    }
    return res
}
linkedin
github
slack

Post Views: 0
Posted in BasicTagged unionfind

Post navigation

LeetCode: Binary String With Substrings Representing 1 To N
LeetCode: Out of Boundary Paths

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.