Problem · Array

Accounts Merge

Learn this problem
MediumOracle logoOracleFULLTIMEONSITE INTERVIEW

Problem statement

Each account is a list of strings. The first string is a person's name and every remaining string is an email address owned by that person.

Two accounts belong to the same person when they share at least one email address. This relationship is transitive: if account A shares an email with account B and account B shares an email with account C, all three accounts must be merged.

Return the merged accounts. Each returned account must contain:

  1. the person's name; then
  2. all unique email addresses in lexicographically ascending order.

For deterministic output, sort the returned accounts by name and then by their first email address. Inputs guarantee that every occurrence of one email address has the same owner name.

Function

accountsMerge(accounts: List<List<String>>) → List<List<String>>

Examples

Example 1

accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]return = [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["John","johnnybravo@mail.com"],["Mary","mary@mail.com"]]

The first two John accounts share johnsmith@mail.com and merge. The other John account shares no email and remains separate.

Example 2

accounts = [["Alex","a@mail.com"],["Alex","b@mail.com"],["Alex","a@mail.com","c@mail.com"]]return = [["Alex","a@mail.com","c@mail.com"],["Alex","b@mail.com"]]

The first and third accounts merge through a@mail.com. Equal names alone do not merge accounts.

Example 3

accounts = [["Solo","only@mail.com"]]return = [["Solo","only@mail.com"]]

A single account is already a complete merged component.

Constraints

  • 1 <= accounts.length <= 1000.
  • 2 <= accounts[i].length <= 10.
  • Names and emails are non-empty strings.
  • The total number of email entries is at most 10^4.
  • Every email address belongs to exactly one owner name.

More Oracle problems

drafts saved locally
public List<List<String>> accountsMerge(List<List<String>> accounts) {
  // write your code here
}
accounts[["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
expected[["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["John","johnnybravo@mail.com"],["Mary","mary@mail.com"]]
checking account