Group Cipher Variants by Scrambled Key
StringsAuto-graded · 15 test casesLast updated
Tests anagram-grouping on structured strings with a prefix/suffix schema, requiring careful key extraction, normalization, and tie-breaking for sorted output.
Group Cipher Variants by Scrambled Key
A cipher registry stores entries in the format:
<prefix>:<body>:<suffix>
- prefix – a non-empty string of lowercase letters (the "namespace")
- body – a non-empty string of lowercase letters (the payload)
- suffix – a single decimal digit character
'0'–'9'(a version tag)
Two entries are considered cipher variants of each other if and only if:
- Their prefixes are identical (same namespace), and
- Their bodies are anagrams of each other (same multiset of characters).
The suffix plays no role in grouping.
Given a list of such entry strings, return a list of groups. Each group is a sorted list of the original entry strings (lexicographic order). The outer list of groups must be sorted by the lexicographically smallest element of each group (ascending).
Entries that share no variant with any other entry still form a group of size one and must be included.
Constraints
1 <= len(entries) <= 2000- Every string in
entriesfollows the<prefix>:<body>:<suffix>format exactly. prefixandbodyeach contain only lowercase ASCII letters (a–z), each with length between 1 and 50.suffixis exactly one digit character ('0'–'9').entriesmay contain duplicate strings; duplicates are treated as distinct entries and grouped together normally.- The returned list of groups (and each inner group) must be exactly as specified—no extra or missing entries, and ordering must match precisely.
Examples
Example 1
Input: group_cipher_variants(['alpha:listen:1', 'beta:enlist:2', 'alpha:silent:3', 'alpha:tinsel:0', 'beta:google:1', 'beta:elgoog:5'])
Output: [['alpha:listen:1', 'alpha:silent:3', 'alpha:tinsel:0'], ['beta:elgoog:5', 'beta:google:1'], ['beta:enlist:2']]
Example 2
Input: group_cipher_variants(['x:abc:0', 'x:bca:1', 'x:cab:2', 'y:abc:3'])
Output: [['x:abc:0', 'x:bca:1', 'x:cab:2'], ['y:abc:3']]
Example 3
Input: group_cipher_variants(['solo:word:9'])
Output: [['solo:word:9']]
Hints
Hint 1
Parse each entry into (prefix, body, suffix); the grouping key is (prefix, sorted(body))—the suffix is irrelevant for grouping.
Hint 2
Use a dict mapping each (prefix, canonical_body) key to the list of original strings that share it; canonical_body is ''.join(sorted(body)).
Hint 3
After grouping, sort each inner list lexicographically, collect all groups into an outer list, then sort that list by its first element.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Parsing and Key Design
Each entry has the form prefix:body:suffix. Split on ":" to extract the three parts. The grouping identity is:
- Same prefix (exact match), and
- Same body anagram class — represented by sorting the body's characters to form a canonical string.
So the dictionary key is the tuple (prefix, "".join(sorted(body))). The suffix is never consulted.
Why This Is Correct
Two strings are anagrams iff they have the same character-frequency multiset. Sorting the characters gives a unique canonical representative for each anagram class, so two bodies produce the same canonical string ↔ they are anagrams. Pairing that with the prefix ensures the first grouping condition is also enforced.
Tie-breaking / Ordering
- Inner sort: each group's entries are sorted lexicographically (Python's default string comparison).
- Outer sort: groups are ordered by their lexicographically smallest element (i.e.,
group[0]after the inner sort).
This gives a fully deterministic, unique output for any input.
Complexity
| Value | |
|---|---|
| Time | O(n · L log L) where n = number of entries, L = max entry length (body sort dominates per entry) |
| Space | O(n · L) for the dictionary and output |
With n ≤ 2 000 and L ≤ 103 characters (50 + 50 + overhead), this is well within limits.
Reference Solution
from typing import List
from collections import defaultdict
def group_cipher_variants(entries: List[str]) -> List[List[str]]:
groups: dict = defaultdict(list)
for entry in entries:
parts = entry.split(":")
prefix = parts[0]
body = parts[1]
# suffix = parts[2] -- ignored for grouping
canonical_body = "".join(sorted(body))
key = (prefix, canonical_body)
groups[key].append(entry)
result = []
for group in groups.values():
result.append(sorted(group))
result.sort(key=lambda g: g[0])
return result