Given a list of words, remove each word that is an anagram of the word immediately before it, and return the remaining words in order.
Problem
You are given an array of strings words.
Build a new array by scanning words from left to right. Keep the first word. For each next word, compare it with the most recently kept word:
- If the two words are anagrams, skip the current word.
- Otherwise, append the current word to the result.
Return the resulting array after all removals are complete.
Two strings are anagrams if they contain the same characters with the same frequencies, possibly in a different order.
Goal
Preserve the relative order of the words that remain after removing consecutive anagrams.
Input Format
- A list
wordsof lowercase strings. - Each word contains only English letters.
Output Format
- Return the filtered array of strings after removing words that are anagrams of the previous kept word.
Constraints
- Words are non-empty lowercase strings.
- The comparison is only against the most recently kept word, not the original previous index if some words were removed.
Example 1
Input
words = ["abba","baba","bbaa","cd","cd"]
Output
["abba","cd"]
Explanation
babais an anagram ofabba, so remove it.bbaais also an anagram of the last kept wordabba, so remove it.cdis not an anagram ofabba, so keep it.- The last
cdis an anagram of the last kept wordcd, so remove it.
Example 2
Input
words = ["a","b","c","d"]
Output
["a","b","c","d"]
Explanation
No adjacent words are anagrams, so nothing is removed.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.