Find Resultant Array After Removing Anagrams - Problem

You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.

In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.

Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".

Input & Output

Example 1 — Basic Anagram Removal
$ Input: words = ["abba","baba","bbaa","cd","cd"]
Output: ["abba","cd"]
💡 Note: "baba" is anagram of "abba" (removed), "bbaa" is anagram of "abba" (removed), second "cd" is anagram of first "cd" (removed)
Example 2 — No Anagrams
$ Input: words = ["a","b","c"]
Output: ["a","b","c"]
💡 Note: No adjacent words are anagrams, so all words remain in the result
Example 3 — All Same Letters
$ Input: words = ["abc","bca","cab"]
Output: ["abc"]
💡 Note: "bca" is anagram of "abc" (removed), "cab" would be anagram of "abc" (removed)

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 10
  • words[i] consists of lowercase English letters

Visualization

Tap to expand
Remove Adjacent Anagrams"abba""baba""bbaa""cd""cd"KeepRemoveRemoveKeepRemove↓ Process Adjacent Pairs ↓"abba""cd"Final Result: ["abba","cd"]
Understanding the Visualization
1
Input Array
["abba","baba","bbaa","cd","cd"]
2
Process
Remove words that are anagrams of their previous word
3
Output
["abba","cd"] - only non-anagram words remain
Key Takeaway
🎯 Key Insight: Sort characters to create a canonical form that makes anagram comparison O(1) after preprocessing
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen