Find Resultant Array After Removing Anagrams

The idea behind the solution is to keep track of each word’s sorted version and check if it is the same as the sorted version of the previous word. If they are the same, it means the two words are anagrams and we should skip the current word.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def removeAnagrams(self, words: List[str]) -> List[str]:
        # Initialize an empty list to hold the result
        result = []
        # Initialize the last_word with the sorted version of the first word in the list
        last_word = sorted(words[0])

        # Add the first word to the result list
        result.append(words[0])

        # Iterate over the rest of the words
        for word in words[1:]:
            # Check if the sorted version of the current word is different from the last word
            if sorted(word) != last_word:
                # If they are different, add the current word to the result list
                result.append(word)
                # And update the last_word with the sorted version of the current word
                last_word = sorted(word)
        # Finally, return the result list
        return result

This solution works by iterating through the words and keeping track of the sorted version of the previous word. When the sorted version of the current word is equal to that of the previous word, it means they are anagrams, so we skip the current word. Otherwise, we add it to the result list and update the sorted version of the last word.