Remove Anagram Duplicates
Given an array of strings words, remove each word that is an anagram of any word that appeared earlier in the array. Return the filtered array preserving the original order of the remaining words.
Two strings are anagrams if they contain the same characters with the same frequencies. The simplest way to check if two words are anagrams is to sort their characters and compare the sorted strings. If the sorted versions are identical, the words are anagrams.
Use a set to track which sorted signatures have already been seen. Iterate through the array in order. For each word, compute its character-sorted signature. If the signature is not in the set, add the word to the result and insert the signature into the set. If it is already in the set, skip the word.
Time complexity is O(n * k log k) where n is the number of words and k is the maximum word length (due to sorting each word's characters). Space complexity is O(n * k) for storing the set of signatures. This approach maintains original order while efficiently detecting anagram duplicates.
Edge cases include an empty array (return empty array), array with one element (return it as-is), and empty strings within the array (sorted empty string is still empty string). Words may contain uppercase and lowercase letters which are treated distinctly.
Example Input & Output
All three are anagrams, keep first only
Empty string element
x repeats but not anagram of y, keep all unique
abba, baba, bbaa are anagrams; keep first. abcd, cdab are anagrams; keep first.
No anagrams, keep all
Algorithm Flow

Solution Approach
Remove words from an array that are anagrams of a previous word, keeping only the first occurrence. Iterate through the array, using a sorted version of each word as a key. If the key has been seen before, skip the word. Otherwise, add it to the result.
Sorting each word produces a canonical key that is identical for all anagrams. The first word with a given key is kept; subsequent ones are removed.
Time complexity is O(n * k log k), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public String[] solution(String[] words) {
Set<String> seen = new HashSet<>();
List<String> res = new ArrayList<>();
for (String w : words) {
char[] ca = w.toCharArray();
Arrays.sort(ca);
String sig = new String(ca);
if (!seen.contains(sig)) {
seen.add(sig);
res.add(w);
}
}
return res.toArray(new String[0]);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
