Katkat

Group Anagrams Without Sorted Character Signatures

AmazonSoftware Engineer · Online Assessment

Last updated

Group anagrams without sorting each word's characters, preserving repeated words and reasoning about frequency signatures and overflow-prone encodings.

Given an array of strings, group all words that are anagrams of one another. Two words are anagrams when every character occurs the same number of times in both words.

Return groups that contain every input occurrence exactly once. Repeated identical words remain repeated occurrences in their group. For deterministic output presentation, list groups by the earliest input occurrence of any member. Within each group, list word occurrences in their original input order. This presentation rule does not change which words belong together.

Input and Output

  • Input: an array of strings over lowercase English letters a through z. For this practice version, an empty word is allowed and all empty words belong in one group. An empty input array returns no groups.
  • Output: an array of anagram groups in the presentation order described above.

Do not create an anagram signature by sorting each word's characters. The source explicitly rules out that per-word sorting approach. The output-order convention does not relax this restriction.

Example

words = ["eat", "tea", "bat", "ate", "bat"]
answer = [["eat", "tea", "ate"], ["bat", "bat"]]

The eat group appears first because its first member is the first input word. Within each group, words retain their input order.

The source also asks about overflow and collision risks of fixed-width prime-product signatures; that discussion is separate from the returned grouping.