KatInterview

Group Scrambled Words by Shared Anagram Fingerprint

StringsAuto-graded · 17 test cases
MediumAuto-gradedStringsstringsanagramshash map

Last updated

Tests the ability to canonicalize strings into sorted-character keys and cluster words that are anagrams of each other, with a precise tie-breaking rule for deterministic output.

Group Scrambled Words by Shared Anagram Fingerprint

A word cluster is a maximal collection of strings that are all anagrams of one another — that is, each string in the cluster contains exactly the same characters with the same frequencies, just potentially in a different order.

Given a list of lowercase strings words, return all word clusters as a list of lists. The output must be ordered and formatted according to the following tie-breaking rules, so that exactly one correct answer exists:

  1. Within each cluster, sort the strings lexicographically (ascending).
  2. Sort the clusters themselves by their lexicographically smallest element (ascending). If two clusters share the same smallest element (impossible by definition, since each string belongs to exactly one cluster), break ties by the second element, and so on — but this case will not arise.

What counts as an anagram?

Two strings are anagrams if and only if they consist of the same multiset of characters. For example, "listen" and "silent" are anagrams; "hello" and "world" are not.

Constraints

  • 0 <= len(words) <= 2000
  • 0 <= len(words[i]) <= 50
  • Every character in words[i] is a lowercase English letter (a–z).
  • words may contain duplicate strings; duplicates are kept (they are trivially anagrams of each other and belong to the same cluster).
  • The empty string "" is a valid word; all empty strings belong to the same cluster.

Examples

Example 1

Input: group_anagram_clusters(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])

Output: [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]

Example 2

Input: group_anagram_clusters([''])

Output: [['']]

Example 3

Input: group_anagram_clusters(['ab', 'ba', 'cd', 'dc', 'abc', 'bca', 'cab'])

Output: [['ab', 'ba'], ['abc', 'bca', 'cab'], ['cd', 'dc']]

Hints

Hint 1

Think about what property two anagram strings always share — what single transformation makes them identical?

Hint 2

Use that shared property as a dictionary key to collect strings into buckets, then apply the required sorting to each bucket and to the list of buckets at the end.

Hint 3

Handle the empty string carefully: it is its own valid key and will form a cluster with any other empty strings in the input.