Find Resultant Array After Removing Anagrams (LeetCode 2273): Solution and Explanation

Easy
Array
Hash Table
String
Sorting

Repeatedly delete any word that is an anagram of the word right before it, and return what is left. The final array is the same whatever order the deletions happen in.

Intuition

Two words are anagrams exactly when they contain the same letters the same number of times. Sorting the letters turns that into a simple string comparison: "baba" and "abba" both become "aabb".

When a word is deleted, its left neighbor becomes the neighbor of the word on its right. Since the deleted word was an anagram of that left neighbor, comparing the next word to the deleted word or to the left neighbor gives the same answer.

So a single left-to-right pass is enough. Track the sorted key of the last word you kept. Each new word is either an anagram of it, and is deleted, or it is not, and becomes the new last kept word.

Because nothing ever looks backward past the last kept word, the order of deletions in the statement does not matter, and one pass reproduces the final array.

Approach: One pass with a sorted key

  1. Start with an empty result and prev = "".
  2. For each word, compute key by sorting its letters.
  3. If key differs from prev, append the word to the result and set prev = key.
  4. If key equals prev, skip the word, since it is an anagram of the last kept word. Return the result.

Step-by-step example

words = ["abba","baba","bbaa","cd","cd"]
  1. "abba" has key "aabb", which differs from the empty prev. Keep it; prev = "aabb".
  2. "baba" and then "bbaa" both have key "aabb", equal to prev, so both are deleted.
  3. "cd" has key "cd", which differs from "aabb". Keep it; prev = "cd".
  4. The last "cd" has key "cd" and is deleted. The result is ["abba","cd"].

Code: Python, Java, C++

1class Solution:
2    def removeAnagrams(self, words: List[str]) -> List[str]:
3        result = []
4        prev = ""
5        for w in words:
6            key = "".join(sorted(w))
7            if key != prev:
8                result.append(w)
9                prev = key
10        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * m log m)

Each of the n words is sorted once, and a word has at most m letters.

Space

O(n * m)

The output can hold every word; the working key needs only O(m).

Other approaches

Letter counts instead of sorting (time O(n * m), space O(n * m))

Compare 26-entry count arrays instead of sorted strings. That is O(m) per word instead of O(m log m), which only matters for long words; here words have at most 10 letters.

Simulate the deletions (time O(n^2 * m log m), space O(n * m))

Repeatedly scan for an adjacent anagram pair and delete it until none is left. It follows the statement literally but can take O(n^2) scans and list deletions.

Common mistakes

  • Comparing each word with words[i - 1] from the original array without thinking about deletions. It happens to give the same answer here, but only because a deleted word is always an anagram of the kept one before it; comparing with the last kept word makes that explicit.
  • Treating words of different lengths as anagrams. Sorted keys of different lengths are never equal, so the key comparison handles it.
  • Deleting both words of an anagram pair. Only the later one is removed; the first stays.
  • Grouping all anagrams in a hash map. Only neighboring anagrams are deleted, so ["ab","cd","ba"] keeps all three words.

Frequently asked questions

Why does the order of deletions not matter?

Every deletion removes a word that is an anagram of its left neighbor, so the word that ends up next to the gap has the same sorted letters as the one removed. Any order produces the same final runs.

Can a word that was kept be deleted later?

No. A word is only deleted because of the word on its left, and the words to the left of a kept word never change once the pass has moved on.

Is a hash map needed?

No. Only the key of the last kept word matters, so a single string variable is enough.