Skip to main content

Command Palette

Search for a command to run...

242. Valid Anagram

Updated
2 min readView as Markdown

definition-An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
We have been given two strings t and s and we have to check if t is an anagram or of s or not.

Simple approach

1:1 checking - or both the strings and then compare them. If they turn out to be equal, we have an anagram.

Alphabet logging

we create two arrays of size 26 , 1 for each alphabet. And keep a record of each alphabet when it comes in both of the strings.
The way i did it is by adding 1 when an alphabet comes in string s (at its corresponding address) and subtracting 1 when the alphabet is in string t. Now, if the resultant array is all 0's then we return true.

But, in the top results in leetcode submissions i found a better optimized solution, specific to this particular problem.

There is a slight issue with the second approach, it can only work with alphabets. But it gets the current job done with high efficiency. Although i am not really sure why there is a flag variable when it is not being used.