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)

Example 1

Input
a (string) = listen
b (string) = silent
Returns (boolean) true

Example 2

Input
a (string) = Triangle
b (string) = Integral
Returns (boolean) true

Example 3

Input
a (string) = apple
b (string) = pale
Returns (boolean) false

Example 4

Input
a (string) = Astronomer
b (string) = Moon starer
Returns (boolean) true

Example 5

Input
a (string) = Hello!
b (string) = oLleh
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.