Merge Accounts Into Groups via Weighted Field Matching
Trees & GraphsAuto-graded · 23 test casesLast updated
Group records into clusters where records are linked when their name/email match score reaches a cutoff, using union-find and bucketing on exact field values.
Merge Accounts Into Groups via Weighted Field Matching
You manage a collection of account records. Each record is a dictionary with three keys:
id: a unique integername: a stringemail: a string
For any two different records, a match score is computed:
- Add
0.6if theiremailstrings are exactly equal. - Add
0.4if theirnamestrings are exactly equal.
So the score is 0.0, 0.4, 0.6, or 1.0.
Two records are directly linked when their score is greater than or equal to the given cutoff.
A group is a maximal set of records connected through direct links, possibly through intermediaries. If A is linked to B and B is linked to C, then A, B, and C belong to the same group, even if A and C are not directly linked.
Every record belongs to exactly one group, and a record with no links forms a group by itself.
Task
Implement group_linked_accounts(accounts, cutoff), which returns the groups as a list of lists of id values.
Output format
- Inside each group, list the ids in ascending order.
- Order the groups by their smallest id, ascending.
- Return
[]ifaccountsis empty.
Rules and edge cases
- Matching is exact and case-sensitive. No normalization is applied, and an empty string matches another empty string.
- If
cutoff <= 0.0, even a score of0.0qualifies, so all records form one group. - If
cutoff > 1.0, no pair can be linked, so every record is its own group. - Compare against the exact scores
0.4,0.6, and1.0. For example, a cutoff of0.4links records that share a name, and a cutoff of0.5links only records that share an email.
Constraints
0 <= len(accounts) <= 10,000- Each
idis a unique integer. nameandemailare strings.cutoffis a float, normally in[0.0, 1.0], but values outside that range must be handled as described above.- An approach that compares every pair of records is too slow to rely on. Aim for near-linear time.
Examples
Example 1
Input: group_linked_accounts([{'id': 1, 'name': 'Alice', 'email': '[email protected]'}, {'id': 2, 'name': 'Alice', 'email': '[email protected]'}, {'id': 3, 'name': 'Bob', 'email': '[email protected]'}], 0.4)
Output: [[1, 2, 3]]
Example 2
Input: group_linked_accounts([{'id': 1, 'name': 'Alice', 'email': '[email protected]'}, {'id': 2, 'name': 'Bob', 'email': '[email protected]'}, {'id': 3, 'name': 'Carol', 'email': '[email protected]'}], 0.6)
Output: [[1], [2], [3]]
Example 3
Input: group_linked_accounts([{'id': 10, 'name': 'A', 'email': 'x'}, {'id': 2, 'name': 'A', 'email': 'y'}, {'id': 7, 'name': 'B', 'email': 'x'}, {'id': 4, 'name': 'C', 'email': 'z'}], 0.7)
Output: [[2], [4], [7], [10]]
Hints
Hint 1
Think of each record as a graph node. The answer is the set of connected components, and union-find (disjoint set union) computes them directly.
Hint 2
The score can only be 0.0, 0.4, 0.6, or 1.0, so the cutoff determines which fields must match. Work out which kind of match is enough for each cutoff range.
Hint 3
Instead of checking pairs, bucket records by the key that must match (name, email, or the pair) and union everything in each bucket with its first member. When a name match alone suffices, an email match also does, so use both buckets.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each record as a node, and add an edge between two records when their score is at least cutoff. The answer is the set of connected components, which union-find (DSU) computes.
Checking all pairs would take about 50 million comparisons at 10,000 records. The score depends only on which fields match, so there is a faster way. There are only four possible scores, which gives a few cutoff ranges:
| Cutoff range | Records are linked when... |
|---|---|
cutoff <= 0.0 | always (score 0 qualifies) |
0.0 < cutoff <= 0.4 | names match or emails match |
0.4 < cutoff <= 0.6 | emails match |
0.6 < cutoff <= 1.0 | names and emails match |
cutoff > 1.0 | never |
For each range, we group records by the key that must match and union all records in a bucket with the first one. For the "name or email" case we build both a name bucket and an email bucket. Records that share a bucket are directly linked, and union-find handles the transitive closure.
Finally, we collect ids by DSU root, sort the ids inside each group, and sort the groups by their smallest id.
Why it is correct
- In each range, two records are directly linked exactly when they fall in a common bucket. In the "name or email" range, a pair with both fields matching shares both buckets, and a pair with only one matching shares that one.
- Unioning every bucket member with the bucket's first member connects the whole bucket, which is the same connectivity as the clique of all pairs in it.
- Union-find merges all connected records, so the resulting sets are exactly the connected components.
- Singletons remain as their own groups, which handles
cutoff > 1.0and records with no shared attributes. - With
cutoff <= 0.0every pair qualifies, so one group results.
Complexity
- Time: O(N · α(N)) for bucketing and unions, plus O(N log N) for sorting the output.
- Space: O(N) for the DSU arrays, buckets, and result.
Reference solution
from collections import defaultdict
from typing import Dict, List
def group_linked_accounts(accounts: List[Dict[str, object]], cutoff: float) -> List[List[int]]:
n = len(accounts)
if n == 0:
return []
parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
def union_buckets(buckets):
for indices in buckets.values():
first = indices[0]
for i in indices[1:]:
union(first, i)
if cutoff <= 0.0:
# Every pair qualifies, even with score 0.
for i in range(1, n):
union(0, i)
elif cutoff <= 0.4:
# A shared name OR a shared email is enough.
buckets = defaultdict(list)
for i, acc in enumerate(accounts):
buckets[("name", acc["name"])].append(i)
buckets[("email", acc["email"])].append(i)
union_buckets(buckets)
elif cutoff <= 0.6:
# Only a shared email is enough.
buckets = defaultdict(list)
for i, acc in enumerate(accounts):
buckets[acc["email"]].append(i)
union_buckets(buckets)
elif cutoff <= 1.0:
# Both name and email must match.
buckets = defaultdict(list)
for i, acc in enumerate(accounts):
buckets[(acc["name"], acc["email"])].append(i)
union_buckets(buckets)
# cutoff > 1.0: no links at all.
groups = defaultdict(list)
for i, acc in enumerate(accounts):
groups[find(i)].append(acc["id"])
result = [sorted(ids) for ids in groups.values()]
result.sort(key=lambda ids: ids[0])
return result