Group Accounts by Shared Identity Fields
Trees & GraphsAuto-graded · 15 test casesLast updated
Tests the ability to model transitive relationships between records using Union-Find (DSU) to identify connected components linked by shared attribute values.
Problem Statement
You are given a list of account records. Each record is a dictionary with four keys:
"id"— a unique integer identifier for the account"tax_id"— a string, orNone"email"— a string, orNone"phone"— a string, orNone
Two accounts are considered related if they share the same non-None value in at least one field (either both have the same tax_id, both have the same email, or both have the same phone).
Relatedness is transitive: if account A is related to B and B is related to C, then A, B, and C all belong to the same cluster, even if A and C share no fields directly.
Write a function that takes this list of account records and returns a list of clusters. Each cluster is a sorted list of id values belonging to the same group. The outer list must be sorted in ascending order by each cluster's first element.
Class / Record Format
Each record is a plain Python dict:
{
"id": int,
"tax_id": str | None,
"email": str | None,
"phone": str | None,
}
Rules and Edge Cases
Nonevalues are ignored when determining relatedness. Two accounts that both haveNonefor a field are not linked through that field.- A
"tax_id"of"123"and a"phone"of"123"do not link two accounts. A match only counts when the same field carries the same value. - An account whose
tax_id,email, andphoneare allNone, or whose values are all unique, forms a cluster of exactly one. - Chains of indirect links must be followed to their full extent: if A–B share a
tax_id, and B–C share aphone, then A, B, and C are one cluster.
Constraints
- Number of accounts
n≤ 10,000 - Each
"id"is a unique positive integer - Field values, when not
None, are non-empty strings - An empty input list returns an empty list
- Output: a list of lists; each inner list is sorted; the outer list is sorted by its first element
Examples
Example 1
Input: group_accounts_by_shared_fields([{'id': 1, 'tax_id': 'T1', 'email': '[email protected]', 'phone': None}, {'id': 2, 'tax_id': 'T1', 'email': None, 'phone': '123'}, {'id': 3, 'tax_id': None, 'email': None, 'phone': '456'}])
Output: [[1, 2], [3]]
Example 2
Input: group_accounts_by_shared_fields([{'id': 1, 'tax_id': None, 'email': '[email protected]', 'phone': None}, {'id': 2, 'tax_id': 'T2', 'email': '[email protected]', 'phone': None}, {'id': 3, 'tax_id': 'T3', 'email': None, 'phone': None}])
Output: [[1, 2], [3]]
Hints
Hint 1
Think about what data structure naturally captures 'same group as' relationships and supports merging groups efficiently.
Hint 2
Instead of comparing every pair of accounts (O(n²)), build a map from (field_name, value) to the first account index that had that value — then you only need one pass to find and union matches.
Hint 3
Make sure your lookup key includes the field name, not just the value. A tax_id of '555' and a phone of '555' are different keys and should not cause a link.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Recognizing the structure
Every account is a node. Two accounts are connected when they share a non-None value in the same field. We need all connected components of that graph. That is a classic Union-Find (DSU) problem.
The naive approach — compare every pair — is O(n²). With n = 10,000 that is 50 million comparisons. We can do much better.
Bucketing by (field, value)
Instead of comparing pairs, we group accounts by attribute. We maintain a dictionary keyed on (field_name, value). For each account, we look at each of its three fields. If the (field, value) pair was seen before, we union the current account with the one that first introduced that key. If not, we record the current account as the owner of that key.
Because Union-Find makes connectivity transitive, a chain like A–B (shared tax_id) and B–C (shared phone) naturally collapses into one component: A and B merge first, then when we process B's phone and find C, we union into the same root.
Why the key must include the field name
If we keyed on the raw value alone, a tax_id of "123" and a phone of "123" would look like a match. The problem only links accounts through the same field, so the key must be (field_name, value), not just value.
Handling None
We skip any field whose value is None. Two accounts that are both None for a field are not linked — they simply have no entry for that key.
Final grouping
After all unions are done, we iterate through the accounts once more, find the DSU root for each, and bucket account ids by root. We then sort each bucket and sort the outer list by its first element to produce a deterministic output.
Correctness
- Soundness: every
unioncall joins two accounts that demonstrably share a non-Nonevalue in the same field, so no false links are created. - Completeness: any two accounts that share
(field, v)both get unioned with the first account that owned(field, v), putting them in the same component. DSU's transitivity handles indirect chains automatically. - Singletons: an account never unioned with anything remains its own root and becomes a one-element cluster.
Complexity
Let k = 3 (the number of fields).
- Time: O(n · k · α(n)) ≈ O(n), where α is the inverse Ackermann function from path compression and union by size.
- Space: O(n · k) for the attribute map, O(n) for the DSU arrays and output.
Reference Solution
from typing import Dict, List
def group_accounts_by_shared_fields(accounts: List[Dict]) -> List[List[int]]:
n = len(accounts)
if n == 0:
return []
parent = list(range(n))
size = [1] * n
def find(x: int) -> int:
# Iterative path compression (halving variant).
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a: int, b: int) -> None:
ra, rb = find(a), find(b)
if ra == rb:
return
# Union by size: attach smaller tree under larger.
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
# Map (field_name, value) -> index of first account seen with that value.
first_seen: Dict = {}
for i, account in enumerate(accounts):
for field in ("tax_id", "email", "phone"):
value = account.get(field)
if value is None:
continue
key = (field, value)
if key in first_seen:
union(i, first_seen[key])
else:
first_seen[key] = i
# Collect accounts by their DSU root.
groups: Dict = {}
for i, account in enumerate(accounts):
groups.setdefault(find(i), []).append(account["id"])
result = [sorted(ids) for ids in groups.values()]
result.sort(key=lambda ids: ids)
return result
Walking through the first example: account 0 (id 1) registers ("tax_id", "T1") and ("email", "[email protected]"). Account 1 (id 2) hits ("tax_id", "T1") which is already owned by index 0, so they are unioned. Account 2 (id 3) registers ("phone", "456") with no prior owner. Final components: {1, 2} and {3}, returned as [[1, 2], [3]].
Note that the DSU indexes accounts by their position in the input list, not by their id. This keeps the arrays dense and works correctly for any hashable id type.