Skip to content
Decoder

Accounts Merge

Medium

Problem

Each entry of accounts is [name, email1, email2, ...]. Two accounts belong to the same person if they share at least one email, and that can chain: if A shares an email with B and B shares one with C, all three are one person. Two people can have the same name, so the name alone proves nothing. Merge the accounts and return one entry per person: the name followed by that person's emails sorted, with no duplicates. The accounts themselves can be returned in any order.

Example 1

accounts = [["Ada", "ada@x.com", "ada_work@x.com"],

Example 2

            ["Ada", "ada@x.com", "ada_home@x.com"],

Example 3

            ["Sam", "sam@x.com"],

Example 4

            ["Ada", "ada2@x.com"]]

Example 5

  →  [["Ada", "ada@x.com", "ada_home@x.com", "ada_work@x.com"],

Example 6

      ["Sam", "sam@x.com"],

Example 7

      ["Ada", "ada2@x.com"]]      (the last Ada shares no email, so she is someone else)

Constraints

  • 1 <= accounts.length <= 1000
  • 2 <= accounts[i].length <= 10
  • Every email is a valid address of at most 30 characters, and every account with a shared email has the same name

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.