Squash Consecutive Letter-Rearrangement Duplicates
StringsAuto-graded · 21 test casesLast updated
Scan a word list and drop each word that is a letter rearrangement of the previously kept word, testing signature comparison and order-preserving single-pass filtering.
You are given a list of lowercase words. Call two words rearrangements of each other if they contain exactly the same letters with the same multiplicities, in any order. Identical words count as rearrangements of each other, and words of different lengths never do.
Consider the following cleanup procedure on the list. As long as there is a position i with 0 < i < len(words) such that the word at position i - 1 and the word at position i are rearrangements of each other, remove the word at position i. Repeat until no such position remains.
Return the list that is left at the end.
Rules
- Only words that are neighbors in the current list are compared. After a removal, the word that slides into position
iis compared with the word now sitting just before it. - The surviving words keep their original relative order.
- The final list does not depend on the order in which eligible removals are carried out, so the answer is unique.
- Return a new list. The input list does not need to be preserved in place, but you should not rely on mutating it.
Constraints
1 <= len(words) <= 1001 <= len(words[i]) <= 10- Each word consists only of lowercase English letters
atoz.
Examples
Example 1
Input: squash_rearranged_neighbors(['listen', 'silent', 'enlist', 'google', 'gogole', 'cat', 'act', 'tac', 'dog'])
Output: ['listen', 'google', 'cat', 'dog']
Example 2
Input: squash_rearranged_neighbors(['a', 'b', 'a', 'a', 'ab', 'ba', 'abc'])
Output: ['a', 'b', 'a', 'ab', 'abc']
Example 3
Input: squash_rearranged_neighbors(['abc', 'abcd', 'dcba', 'bcad'])
Output: ['abc', 'abcd']
Hints
Hint 1
Rearrangement is an equivalence relation: two words are rearrangements exactly when their sorted letters (or 26-letter count vectors) are equal. Think about what that means for chains of removals.
Hint 2
You do not need to simulate removals in the middle of a list. Build the result as you scan, and compare each new word only with the last word you decided to keep.
Hint 3
Comparing with the last kept word is equivalent to comparing with the original predecessor, because any removed word had the same letters as the kept word before it. Non-adjacent repeats and words of different lengths need no special handling.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Give each word a signature: its letters in sorted order. Two words are rearrangements of each other exactly when their signatures are equal. This already covers identical words and automatically rejects words of different lengths.
Because "same signature" is an equivalence relation (in particular, transitive), the removal process boils down to this: every maximal run of consecutive words sharing one signature collapses to the first word of that run. All other words survive in their original order.
So a single left-to-right scan suffices. Keep an output list and the signature of its last element:
- If the output is non-empty and the current word has the same signature as the last kept word, skip it.
- Otherwise, append it and remember its signature.
Why it is correct
- Skipping is forced. Everything between the last kept word and the current word has already been removed, so the current word's left neighbor in the current list is the last kept word. If they are rearrangements, the rule requires removing the current word.
- Keeping is safe. If the current word is not a rearrangement of the last kept word, it is never eligible for removal: its left neighbor is fixed, since kept words are never removed later. Later words only affect what lies to its right.
- Last kept versus original predecessor. If the original predecessor was removed, it had the same signature as the last kept word, so by transitivity comparing against either gives the same answer. This handles chains like
["abc", "abcd", "dcba", "bcad"], where both"dcba"and"bcad"are removed. - Uniqueness. The result is "the first word of each maximal same-signature run", which does not depend on the order of removals.
Non-adjacent repeats such as the two "a" words in ["a", "b", "a"] are never compared, so both stay.
Complexity
Let n be the number of words and L the maximum word length.
- Time:
O(n * L log L), since each word is sorted once. Using letter-count tuples would giveO(n * L). - Space:
O(n)for the output, plusO(L)for the current signature.
Reference solution
def squash_rearranged_neighbors(words: list[str]) -> list[str]:
kept = []
last_sig = None
for w in words:
sig = sorted(w)
if kept and sig == last_sig:
continue
kept.append(w)
last_sig = sig
return kept