Implement the method isAnagram that takes two strings and returns true if they are anagrams of each other, otherwise returns false.

Intermediate Level
String Manipulation Hash Map

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)
Example 1
Input:
a (string) = listen
b (string) = silent
Return:
(boolean) true
Example 2
Input:
a (string) = Triangle
b (string) = Integral
Return:
(boolean) true
Example 3
Input:
a (string) = apple
b (string) = pale
Return:
(boolean) false
Example 4
Input:
a (string) = Astronomer
b (string) = Moon starer
Return:
(boolean) true
Example 5
Input:
a (string) = Hello!
b (string) = oLleh
Return:
(boolean) true

To check if two strings are anagrams:

  1. Sanitize both strings
    • Remove non-alphanumeric characters
    • Convert to lowercase
  2. Count character frequencies
    • If both strings have the same frequency for all characters, they are anagrams.
  3. Compare the results
    • Return true if both match; otherwise, return false.

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
Run your code to see the result.