Intermediate Level
Implement the method isAnagram that takes two strings and returns true if they are anagrams of each other, otherwise returns false.
Two strings are called anagrams if they contain the same characters with the same frequency, but possibly in a different order.
- The comparison should be case-insensitive.
- Spaces and punctuation should be ignored.
For example:
"listen"and"silent"→ ✅ Anagrams"Hello"and"oLleh"→ ✅ Anagrams"test"and"taste"→ ❌ Not Anagrams (different letters)
To check if two strings are anagrams:
- Sanitize both strings
- Remove non-alphanumeric characters
- Convert to lowercase
- Count character frequencies
- If both strings have the same frequency for all characters, they are anagrams.
- Compare the results
- Return
trueif both match; otherwise, returnfalse.
- Return
Pseudocode:
Function isAnagram(s1, s2):
Clean s1 and s2:
- Remove all non-alphanumeric characters
- Convert to lowercase
If length of s1 ≠ length of s2:
Return false
Create a frequency map for s1
Create a frequency map for s2
If both frequency maps are equal:
Return true
Else:
Return false