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…


This content originally appeared on DEV Community and was authored by Jeyaprasad R

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

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.


This content originally appeared on DEV Community and was authored by Jeyaprasad R


Print Share Comment Cite Upload Translate Updates
APA

Jeyaprasad R | Sciencx (2026-03-20T01:10:54+00:00) Valid Anagram. Retrieved from https://www.scien.cx/2026/03/20/valid-anagram-2/

MLA
" » Valid Anagram." Jeyaprasad R | Sciencx - Friday March 20, 2026, https://www.scien.cx/2026/03/20/valid-anagram-2/
HARVARD
Jeyaprasad R | Sciencx Friday March 20, 2026 » Valid Anagram., viewed ,<https://www.scien.cx/2026/03/20/valid-anagram-2/>
VANCOUVER
Jeyaprasad R | Sciencx - » Valid Anagram. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2026/03/20/valid-anagram-2/
CHICAGO
" » Valid Anagram." Jeyaprasad R | Sciencx - Accessed . https://www.scien.cx/2026/03/20/valid-anagram-2/
IEEE
" » Valid Anagram." Jeyaprasad R | Sciencx [Online]. Available: https://www.scien.cx/2026/03/20/valid-anagram-2/. [Accessed: ]
rf:citation
» Valid Anagram | Jeyaprasad R | Sciencx | https://www.scien.cx/2026/03/20/valid-anagram-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.