Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

Valid Anagram

Valid Anagram

Problem Statement

Given two strings s and t, determine if t is an anagram of s.

An anagram is a word formed by rearranging the letters of another word using all the original characters exactly once.


Examples

Input
s = "anagram"
t = "nagaram"

Output
True


Input
s = "rat"
t = "car"

Output
False


Approach 1 Using Sorting

Sort both strings and compare them.


Steps

1 Sort string s
2 Sort string t
3 Compare both sorted strings


Code

```python id="ana1"
def isAnagram(s, t):
return sorted(s) == sorted(t)




---

## Approach 2 Using Frequency Count

Count the frequency of each character and compare.

---

### Steps

1 Create a dictionary to count characters in s
2 Traverse string t and reduce count
3 If any mismatch occurs return False

---

### Code



```python id="ana2"
def isAnagram(s, t):
    if len(s) != len(t):
        return False

    count = {}

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

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

    return True
Enter fullscreen mode Exit fullscreen mode

Explanation

The sorting method compares ordered strings.
The frequency method ensures both strings have the same characters with the same count.


Expected Output

Input
s = "anagram"
t = "nagaram"

Output
True


Conclusion

Valid Anagram is a simple and important problem that helps in understanding strings and character counting. It is commonly asked in coding interviews.

Practice this problem to improve your string handling skills.

Top comments (0)