DEV Community

Jeyaprasad R
Jeyaprasad R

Posted on

Valid Anagram

In this task, I worked on checking whether two given strings are anagrams of each other. Anagrams are words that contain the same characters but arranged in a different order.

What I Did

I created a function isAnagram that takes two strings as input and returns True if they are anagrams, otherwise False.

For example:
Input: s = "listen", t = "silent"
Output: True

How I Solved It

First, I checked if both strings have the same length. If they don’t, they cannot be anagrams.

Then I used a dictionary to count how many times each character appears in the first string.

After that, I went through the second string:

  • If a character is not in the dictionary or its count is already zero, I return False
  • Otherwise, I decrease the count for that character

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        count = {}

        for c in s:
            count[c] = count.get(c, 0) + 1

        for c in t:
            if c not in count or count[c] == 0:
                return False
            count[c] -= 1

        return True
Enter fullscreen mode Exit fullscreen mode

How It Works

The dictionary keeps track of how many times each character appears. As we process the second string, we reduce those counts.

If both strings have exactly the same characters with the same frequency, all counts will match correctly, and the function returns True.

Top comments (0)