Problem Description
Given an array of strings, remove every word that is an anagram of the previous word (i.e. any adjacent pair that are anagrams). Continue performing this operation until no such adjacent anagram exists, and return the resulting array.
Key Insights
- Two words are anagrams if their sorted characters are identical.
- Only adjacent words need to be compared.
- The order of operations does not affect the final result.
- A single-pass solution using a stack (or result list) is sufficient.
Space and Time Complexity
Time Complexity: O(n * m log m), where n is the number of words and m is the maximum length of a word (due to sorting each word).
Space Complexity: O(n * m), for storing the result list and the sorted character arrays.
Solution
We use a greedy one-pass approach with a result list (or stack).
- Initialize the result with the first word of the input array.
- Iterate through the remaining words. For each word, compare its sorted character sequence with that of the last word in the result list.
- If they are not equal (i.e. not anagrams), add the word to the result list.
- Return the final result list.
This works because removing a word when it is an anagram of its predecessor leads to the same final set irrespective of the order of removals.