Find Resultant Array After Removing Anagrams

You are given a 0-indexed string array `words` of lowercase English letters. In one operation, pick an index `i` with `0 < i < words.length` such that `words[i - 1]` and `words[i]` are anagrams, and delete `words[i]`. Keep doing this while any such index exists. Return `words` after all operations. The result is the same no matter which order the operations are done in. An anagram is a word formed by rearranging all the letters of another word, using each letter exactly once.

30:00

Find Resultant Array After Removing Anagrams
easy
Free written solution
Topics
Companies

You are given a 0-indexed string array words of lowercase English letters. In one operation, pick an index i with 0 < i < words.length such that words[i - 1] and words[i] are anagrams, and delete words[i]. Keep doing this while any such index exists.

Return words after all operations. The result is the same no matter which order the operations are done in. An anagram is a word formed by rearranging all the letters of another word, using each letter exactly once.

Example 1:
Input: {"words":["abba","baba","bbaa","cd","cd"]}
Output: ["abba","cd"]
Constraints:
  • 1≤words.length≤1001 \leq \text{words.length} \leq 100

  • 1≤words[i].length≤101 \leq \text{words}[i].\text{length} \leq 10

  • words[i] consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["abba","baba","bbaa","cd","cd"]}

A deleted word is always an anagram of the word kept just before it, so compare each word with the last kept word only. Anagrams share the same sorted letters.

words

abba

0

baba

1

bbaa

2

cd

3

cd

4

result (0)

empty

Variables
VariableValue
result[]
prev""
DepthFunction Call
Stack empty
0/11