Show problems as
Classic problem #721MediumArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-FindSorting

Accounts Merge

Real-world version: Merge Crew Badge Records
Tracked in this browser only
Read Accounts Merge on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstFinding Connected Components · Graphs, animated step by step

Every gate at a depot keeps its own badge log, so one crew member can show up in several logs. You are handed records, where records[i] starts with the crew member's display name and continues with the badge codes that were scanned under that name at one gate.

Badge codes identify a person: if two records list a code in common, they were written by the same crew member. Follow that through as far as it goes, so records linked by a chain of shared codes are all the same person even when no single code is in all of them. One crew member always signs with one display name, though it is quite possible for two unrelated crew members to sign with the very same one, so the display name on its own tells you nothing.

Return one entry per crew member: the display name, followed by that person's badge codes with duplicates removed and sorted in increasing lexicographic order. The entries themselves may come back in any order.

Examples

Example 1

Input
records = [["Nadia", "kx7", "qp2"], ["Omar", "zz1"], ["Nadia", "qp2", "tt9"], ["Nadia", "aa0"]]
Output
[["Nadia", "kx7", "qp2", "tt9"], ["Omar", "zz1"], ["Nadia", "aa0"]]

The first and third records share qp2, so they came from one crew member. The fourth shares nothing with them and belongs to a different crew member who happens to sign the same way.

Example 2

Input
records = [["Sam", "p1", "p2"], ["Sam", "p3", "p4"], ["Sam", "p2", "p3"]]
Output
[["Sam", "p1", "p2", "p3", "p4"]]

The first two records look unrelated until the third links p2 to p3, which pulls all three into one crew member.

Example 3

Input
records = [["Ivy", "zz9", "aa1"]]
Output
[["Ivy", "aa1", "zz9"]]

A single record still has to come back with its codes in increasing order.

Constraints

  • 1 <= records.length <= 1000
  • 2 <= records[i].length <= 10
  • 1 <= records[i][j].length <= 30
  • records[i][0] consists of English letters.
  • records[i][j] for j > 0 consists of lowercase English letters and digits.

The values you return may be in any order.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def merge_badge_records(records: list[list[str]]) -> list[list[str]]:
Java
public List<List<String>> mergeBadgeRecords(List<List<String>> records)