Keep Words Whose Letter Multiset Appears More Than Once
Arrays & HashingAuto-graded · 20 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two words are rearrangements of each other exactly when their letter-count vectors are equal. So each word is mapped to a key: a tuple of 26 integers, where position i holds how many times the i-th letter of the alphabet occurs in the word.
A word cannot be accepted or rejected when first seen, because a later word may make it qualify (for example "eat" followed by "tea"). So the solution uses two passes:
- Count pass: compute each word's key, store it, and increment a counter for that key in a dictionary.
- Select pass: walk the words in input order and keep each word whose key has a tally greater than 1.
Why it is correct
- Equal count vectors hold if and only if the words are rearrangements, so the tally for a key is exactly the size of that group of entries.
- An entry qualifies if and only if its group has at least two entries, i.e. its tally is above 1. The tally table is complete before selection begins, so earlier words correctly see later group members.
- The result is a filter over the original list, so order is preserved and duplicates are kept naturally.
- Identical words land on the same key, so two copies of the same word both qualify.
- The empty string maps to the all-zero tuple, so two empty strings share a key and both qualify; a single one does not.
Why not a set of letters, and why not sorting
A set of distinct letters ignores multiplicity: "ab" and "aab" would both give {a, b} and be wrongly grouped. Count vectors keep a:1, b:1 and a:2, b:1 distinct.
Sorting each word's letters is also correct, but costs O(k log k) per word of length k. Because the alphabet is fixed at 26 letters, counting costs O(k) per word plus O(26) to build and hash the tuple, which keeps the total linear.
Complexity
With n words and L total letters:
- Time: O(L + n), since each letter is counted once and each word costs a constant 26-slot key.
- Space: O(n) for the stored keys, the tally table and the output (each key has a fixed size of 26).
Reference solution
from typing import List
def repeated_anagram_words(words: List[str]) -> List[str]:
keys = []
tally = {}
# Pass 1: build a letter-count key per word and count how many words share it.
for word in words:
counts = [0] * 26
for ch in word:
counts[ord(ch) - 97] += 1
key = tuple(counts)
keys.append(key)
tally[key] = tally.get(key, 0) + 1
# Pass 2: keep words, in original order, whose key is shared by 2+ words.
return [w for w, key in zip(words, keys) if tally[key] > 1]