KatInterview

Keep Words Whose Letter Multiset Appears More Than Once

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashinghash-mapanagramscounting

Last updated

Filter a word list to the entries whose letter multiset is shared by at least two entries, keeping input order and duplicates, using letter-count keys.

You are given a list of lowercase words. Two words are rearrangements of each other when they contain exactly the same letters with exactly the same number of occurrences each, in any order.

Write a function that returns every entry of the list that has at least one other entry in the list (at a different position) that is a rearrangement of it. Entries whose letter multiset is unique in the list must be left out.

Rules

  • Return the qualifying entries in the same order in which they appear in the input.
  • Do not sort the words and do not remove duplicates from the output. Each qualifying position in the input contributes one element to the result.
  • Two entries that are the same word are rearrangements of each other, so a word that appears twice qualifies even if no other rearrangement exists.
  • Letter counts matter: "ab" and "aab" are not rearrangements of each other.
  • The empty string has no letters. If it appears at least twice, every empty entry qualifies. If it appears once, it does not.
  • If nothing qualifies, return an empty list.

Constraints

  • At most 100000 words in the list.
  • At most 1000000 letters in total across all words.
  • Every word consists only of lowercase English letters a-z; words may be empty.
  • Target running time is linear in the number of words plus the total number of letters.

Examples

Example 1

Input: repeated_anagram_words(['eat', 'tea', 'bat', 'eat', 'tan', 'nat', 'solo'])

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

Example 2

Input: repeated_anagram_words(['a', 'ab', 'aab', ''])

Output: []

Hints

Hint 1

An entry can qualify because of a word that appears later in the list, so you cannot decide whether to keep it the moment you read it.

Hint 2

Build a key for each word that is identical for rearrangements and different otherwise. A set of the distinct letters loses how many times each letter occurs, so it is not enough.

Hint 3

Use a 26-slot count of letters as the key, converted to a tuple so it can be hashed. First tally how many words share each key, then walk the list again in order and keep words whose key tally is at least 2.