DEV Community

Haripriya V
Haripriya V

Posted on

ASSIGNMENT 14

  1. Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Problem
Given two strings s and t, check whether t is an anagram of s.
--> An anagram means:
Same characters
Same frequency
Order doesnโ€™t matter

Example:
Id="ex7"
Input: s = "anagram", t = "nagaram"

Output: True

**Approach Used: **Frequency Count (Optimized)
Instead of sorting, we:
Count character frequencies
Compare counts

CODE:

`class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False

    arr = [0] * 26

    for i in range(len(s)):
        arr[ord(s[i]) - ord('a')] += 1
        arr[ord(t[i]) - ord('a')] -= 1

    for check in arr:
        if check != 0:
            return False
    return True`
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1) (fixed 26 array)

Conclusion
Frequency counting is the most efficient approach
Your method is:
Fast
Memory efficient
Ideal for constrained inputs

Top comments (0)