You are given a 0-indexed string array words
, where words[i]
consists of lowercase English letters. In one operation, select any words[i]
and remove it if words[i-1]
is an anagram of words[i]
. You must repeatedly perform this operation until no adjacent elements in the array are anagrams of each other. Return words
after performing all operations.
To ensure we understand the requirements correctly, let’s clarify a few points:
words[i-1]
and words[i]
?
are_anagrams(word1, word2)
to determine if two words are anagrams by comparing their sorted characters.K
is the maximal length of any word in the list.N
is the number of words in the list.Here is the implementation of the strategy described:
def are_anagrams(word1, word2):
return sorted(word1) == sorted(word2)
def remove_anagrams(words):
stack = []
for word in words:
if stack and are_anagrams(stack[-1], word):
stack.pop() # remove the last word if it is an anagram with the current word
else:
stack.append(word)
return stack
# Example usage:
words = ["abba", "baba", "bbaa", "cd", "dc"]
print(remove_anagrams(words)) # Output should be ['abba', 'cd']
K
is the maximum length of the words in the array.N
is the number of words.This should yield the correct resultant array after removing all adjacent anagrams as specified.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?