Leetcode 2273. Find Resultant Array After Removing Anagrams
You are given a 0-indexed string array words
, where words[i]
consists of lowercase English letters. In one operation, you can remove any anagram of words[i]
in words
, if there is one. You need to return the resultant array after removing all anagrams.
An anagram of a word is a word that can be rearranged to form the same word. For instance, “baba” and “aabb” are anagrams of each other, however, “bbaa” and “abb” are not anagrams.
words = ["abba","baba","bbaa","cd","dc"]
["abba","cd"]
1 <= words.length <= 100
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.This approach will ensure every group of anagrams appears only once in the output list, with the first occurrence preserved.
import java.util.*;
public class Solution {
public List<String> removeAnagrams(String[] words) {
List<String> result = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (String word : words) {
char[] charArray = word.toCharArray();
Arrays.sort(charArray);
String sortedWord = new String(charArray);
if (!seen.contains(sortedWord)) {
result.add(word);
seen.add(sortedWord);
}
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
String[] words = {"abba", "baba", "bbaa", "cd", "dc"};
List<String> result = sol.removeAnagrams(words);
System.out.println(result); // Output: ["abba", "cd"]
}
}
O(m log m)
where m
is the length of the word.n
words each of maximum length m
, the total time complexity is O(n * m log m)
for sorting.O(n * m)
for storing the resultant list and set of seen words.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?