#2273
Find Resultant Array After Removing Anagrams
EasyArrayHash TableStringSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * k log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * k log k)Space O(n)
The optimal approach uses a HashSet to track unique sorted versions of words. This allows us to efficiently determine if a word is an anagram of any previously seen word.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list for the result and a HashSet to track seen sorted words.
- 2Step 2: Iterate through each word in the input list.
- 3Step 3: Sort the current word and check if it exists in the HashSet. If it does, skip it; if not, add it to both the HashSet and the result list.
solution.py10 lines
1# Full working Python code
2words = ["abba", "baba", "bbaa", "cd", "cd"]
3result = []
4seen = set()
5for word in words:
6 sorted_word = ''.join(sorted(word))
7 if sorted_word not in seen:
8 seen.add(sorted_word)
9 result.append(word)
10print(result)ℹ
Complexity note: Here, n is the number of words and k is the average length of the words. Sorting each word takes O(k log k), and we store each unique sorted word in a HashSet.
- 1Understanding anagrams requires recognizing that they have the same characters in different orders.
- 2Using sorting or frequency counting can help identify anagrams efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.