DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Valid Anagram – Check if Two Strings are Anagrams

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

Example:
Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Approach:
We count the frequency of each character in string s and then reduce the count using string t. If all counts become zero, the strings are anagrams.

Code:

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 algorithm ensures both strings have the same characters with the same frequency. If any mismatch occurs, it returns false.

Time Complexity:
O(n), where n is length of string

Space Complexity:
O(1), since only 26 lowercase letters are used

Top comments (0)