DEV Community

Santhosh V
Santhosh V

Posted on

CA 14 - Valid Anagram

Problem

Given two strings s and t, the task is to check whether t is an anagram of s.

An anagram means both strings contain the same characters with the same frequency.

Output

Example 1
Output: true
Example 2
Output: false
Enter fullscreen mode Exit fullscreen mode

My Approach

To solve this problem, I used a frequency count method.

First, I check if both strings have the same length. If not, they cannot be anagrams.

Then I create a dictionary to count the frequency of each character in string s.

Next, I iterate through string t:

If a character is not in the dictionary, return false
Otherwise, decrease its count

At the end, if all counts are zero, both strings are anagrams.

This works because both strings must have exactly the same characters with the same frequency.

This approach is efficient because:

It requires one traversal of both strings
It uses minimal extra space
Code

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = {}
    for ch in s:
        count[ch] = count.get(ch, 0) + 1
    for ch in t:
        if ch not in count:
            return False
        count[ch] -= 1
    return all(v == 0 for v in count.values())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)