Group Anagram Chains by Transformation Distance
StringsAuto-graded · 17 test casesLast updated
Tests anagram grouping combined with string parsing and multi-key sorting to build and rank clusters of anagrammatically related words from a structured input.
Group Anagram Chains by Transformation Distance
You are given a list of tokens, where each token is a non-empty string of the form:
<word>:<weight>
<word>is a non-empty string consisting only of lowercase English letters (a–z).<weight>is a non-negative integer with no leading zeros (except"0"itself).
Parse each token into its word and weight. Then group the words by their anagram signature (two words are anagrams of each other if and only if they contain exactly the same letters with the same frequencies, ignoring the word's position in the list).
For each anagram group produce a group record: a dict with these keys:
| Key | Value |
|---|---|
"members" | Sorted list of distinct words in the group (lexicographic order). Duplicates (same word appearing multiple times across tokens) are deduplicated. |
"total_weight" | Sum of weights of all tokens whose word belongs to this group (including duplicate word occurrences). |
"size" | Number of distinct words in the group. |
Return the list of group records sorted by the following tie-breaking rules (earlier rules take priority):
- Descending
"total_weight". - Descending
"size". - Ascending
"members"[0](lexicographic order on the first member, after the member list is sorted).
Constraints
1 ≤ len(tokens) ≤ 2 000- Each token matches the pattern
<word>:<weight>exactly once (one colon, word left, weight right). 1 ≤ len(word) ≤ 50for each word in any token.0 ≤ weight ≤ 10 000for each weight.- Words consist only of lowercase English letters.
- A word may appear in multiple tokens with different weights; all such tokens contribute to
total_weight. - Groups with only one distinct word are valid and must be included.
- The returned list must contain exactly one record per anagram equivalence class found among the parsed words.
Examples
Example 1
Input: group_anagram_chains(['eat:10', 'tea:5', 'tan:3', 'ate:7', 'nat:2', 'bat:8'])
Output: [{'members': ['ate', 'eat', 'tea'], 'total_weight': 22, 'size': 3}, {'members': ['bat'], 'total_weight': 8, 'size': 1}, {'members': ['nat', 'tan'], 'total_weight': 5, 'size': 2}]
Example 2
Input: group_anagram_chains(['abc:100', 'bca:50', 'cab:25', 'xyz:200', 'zyx:1'])
Output: [{'members': ['xyz', 'zyx'], 'total_weight': 201, 'size': 2}, {'members': ['abc', 'bca', 'cab'], 'total_weight': 175, 'size': 3}]
Example 3
Input: group_anagram_chains(['hello:0', 'world:0', 'dlrow:0'])
Output: [{'members': ['dlrow', 'world'], 'total_weight': 0, 'size': 2}, {'members': ['hello'], 'total_weight': 0, 'size': 1}]
Hints
Hint 1
Sort the characters of each word to build a canonical anagram key, then use a dictionary to group tokens by that key.
Hint 2
Be careful to deduplicate words for the 'members' list and 'size' count, but sum ALL token weights (including repeated words) for 'total_weight'.
Hint 3
Apply the three-level sort at the end: (-total_weight, -size, members[0]).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Parsing
Split each token at the colon to extract word and weight. The colon index is found with str.index(":") which handles the single-colon guarantee cleanly.
Anagram Key
Sort the characters of word to form a canonical key (e.g., "eat" → "aet"). All words sharing the same key are anagrams.
Grouping
Use a defaultdict keyed by the anagram signature. For each entry track:
words: a Pythonsetto deduplicate distinct words.total_weight: accumulate every token's weight (including repeated words).
This directly handles the subtle distinction: "members" / "size" use distinct words, but "total_weight" counts every occurrence.
Building Records
For each signature group, sort words lexicographically to form members, then build the result dict.
Sorting
Sort the records with a compound key:
(-total_weight, -size, members[0])
This implements: highest weight first, break ties by larger group, break further ties by first member alphabetically.
Correctness
- Single-word groups are included naturally (any word that has no anagram partner forms its own group).
- Duplicate tokens for the same word correctly add to
total_weightbut do not inflatesize. - The sort key is deterministic and total, so the output is unique.
Complexity
- Time: O(N · L log L + G log G) where N = number of tokens, L = max word length, G = number of distinct anagram groups (G ≤ N).
- Space: O(N · L) to store all words and keys.
from typing import List
from collections import defaultdict
def group_anagram_chains(tokens: List[str]) -> List[dict]:
groups = defaultdict(lambda: {"words": set(), "total_weight": 0})
for token in tokens:
colon_idx = token.index(":")
word = token[:colon_idx]
weight = int(token[colon_idx + 1:])
key = "".join(sorted(word))
groups[key]["words"].add(word)
groups[key]["total_weight"] += weight
records = []
for key, data in groups.items():
members = sorted(data["words"])
records.append({
"members": members,
"total_weight": data["total_weight"],
"size": len(members),
})
records.sort(key=lambda r: (-r["total_weight"], -r["size"], r["members"][0]))
return records