Skip to main content
Back to problems
#2273
Easy Algorithms

Find resultant array after removing anagrams

Array Hash Table String Sorting
69.9% acceptance
Feb 25, 2026
1057
238
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".

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn remove_anagrams(words: Vec<String>) -> Vec<String> {
    let sorted = |w: &String| -> Vec<u8> {
      let mut b: Vec<u8> = w.bytes().collect();
      b.sort_unstable();
      b
    };
    let mut result: Vec<String> = Vec::new();
    for word in words {
      if result.last().map_or(true, |last| sorted(last) != sorted(&word)) {
        result.push(word);
      }
    }
    result
  }
}