Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Sorting
Hash Maps
Find Resultant Array After Removing Anagrams

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.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

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 words of 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

  • 1words1 \le |words|
  • 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.
Examples
Sample cases returned by the problem API.

Example 1

Input

words = ["abba","baba","bbaa","cd","cd"]

Output

["abba","cd"]

Explanation

  • baba is an anagram of abba, so remove it.
  • bbaa is also an anagram of the last kept word abba, so remove it.
  • cd is not an anagram of abba, so keep it.
  • The last cd is an anagram of the last kept word cd, 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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.