KatInterview

Squash Consecutive Letter-Rearrangement Duplicates

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringsstringsanagramssimulation

Last 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 i is 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) <= 100
  • 1 <= len(words[i]) <= 10
  • Each word consists only of lowercase English letters a to z.

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.