Problem
LeetCode 242: Valid Anagram
Solution
| |
Explaination
For two strings to be anagrams
- They have to be the same length.
- The composition of their alphabet is the same, but the order will vary.
Let me show you three ways to solve this problem. We construct two hashmaps/dictionaries where the value is the number of their appearances and the key is the alphabet. You compare the two dicts once you’ve constructed them.
It can also be solved with sets and the str.count method. To remove duplicates, you convert one of the strings to a set. Next, we compare the number of letters in each string. We have anagrams if everything matches.
There is a one line solution to this problem using collections.Counter.
Reference
Also see
- Concatenation of Array
- Contains Duplicate
- Two Sum
- Longest Common Prefix
- Group Anagrams
- Remove Element
- Majority Element
- Design HashSet
- Design HashMap
- Sort an Array
- Sort Colors
- Top K Frequent Elements
- Encode and Decode Strings
- Range Sum Query 2D Immutable
- Product of Array Except Self
- Valid Sudoku
- Longest Consecutive Sequence
- Best Time to Buy And Sell Stock II
- Majority Element II
- Subarray Sum Equals K
- First Missing Positive