KatInterview

Group Cipher Variants by Scrambled Key

StringsAuto-graded · 15 test cases
MediumAuto-gradedStringsstringsanagram groupingsorting

Last 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:

  1. Their prefixes are identical (same namespace), and
  2. 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 entries follows the <prefix>:<body>:<suffix> format exactly.
  • prefix and body each contain only lowercase ASCII letters (a–z), each with length between 1 and 50.
  • suffix is exactly one digit character ('0'–'9').
  • entries may 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.