Meta Data#
Difficulty: easy First Attempt: 2026-01-29
- Submissions: Accepted (first try)
Approach#
After deleting words[i], the next word’s “previous” becomes words[i - 1]. The deleted word was an anagram of words[i - 1], and anagrams are transitive, so comparing with either gives the same result.
So scan left to right and compare only with the last kept word: keep it if not an anagram. Check anagrams with sorted strings (Hash Table Template 5).
My Solution#
I originally went right to left, comparing neighbors with Counter and popping when equal. Here it builds a new list left to right:
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
res = []
for w in words:
if not res or sorted(res[-1]) != sorted(w):
res.append(w)
return res
Complexity#
Time O(n · L log L) for word length L, space O(n · L).
Mistakes to Avoid#
popinside a loop shifts indices; it is only safe right to left, and building a new list is simpler.
Interview Explanation#
After a deletion the next word compares with the one before the deleted word; anagrams are transitive, so that equals comparing with the last kept word. I scan left to right and keep a word when its sorted form differs from the last kept one. Time O(n L log L).
