DEV Community

Anjana R.K.
Anjana R.K.

Posted on • Edited on

Valid Anagram

Hi everyone!
Today I solved a string problem where we need to check whether two strings are anagrams of each other.

Problem
Given two strings s and t, return True if t is an anagram of s, else return False.

An anagram means both strings have the same characters with same frequency, just arranged differently.

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

Output: True

My Approach
At first, I thought of sorting both strings and comparing them.
But that would take O(n log n) time.
Then I used a better approach:

Count character frequencies using an array

Logic

If lengths are different

return False

Create a count array of size 26 (for lowercase letters)

Traverse both strings together:

Increase count for s
Decrease count for t

At the end, if all values are 0 ,then it is anagram.

Code (Python)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

    count = [0] * 26

    for a, b in zip(s, t):
        count[ord(a) - ord('a')] += 1
        count[ord(b) - ord('a')] -= 1

    return all(c == 0 for c in count)
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity

Time: O(n)
Space: O(1) (fixed size array)

Key Insight

Instead of sorting, we can use frequency counting, which is faster and more efficient.

What I Learned

Frequency arrays are useful for string problems
Avoid sorting when linear solutions exist
ord() helps map characters to indices

Thanks for reading!
Feel free to share other approaches like hashmap or sorting.

Top comments (0)