Valid Anagram - LeetCode Problem
Table of contents
Problem Description
The "Valid Anagram" problem is given two strings s and t, write a function to determine if t is an anagram of s.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example, "listen" is an anagram of "silent".
Solution
In this problem, we need to check if two strings are anagrams. In other words, we need to check if they have the same characters but in a different order.
To solve this problem, we can use a hash table. First, we check if the lengths of the two strings are the same. If they are not, then they cannot be anagrams.
Next, we create a hash table of size 128 (the number of ASCII characters). We iterate through the first string and increment the value of the character's ASCII code in the hash table. Then, we iterate through the second string and decrement the value of the character's ASCII code in the hash table. If at any point we find that the value of a character's ASCII code in the hash table is negative, then we know that the second string has a character that is not present in the first string.
If we have iterated through both strings without finding any inconsistencies, then the two strings are anagrams.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
table = [0] * 128
for c in s:
table[ord(c)] += 1
for c in t:
table[ord(c)] -= 1
if table[ord(c)] < 0:
return False
return True
Complexity Analysis
The time complexity of this solution is O(n), where n is the length of the strings. We iterate through each character in the strings only once.
The space complexity of this solution is O(1), since we are using a fixed-size hash table of size 128.
Conclusion
This problem is a great example of how hash tables can be used to solve problems efficiently. With a little bit of knowledge about ASCII codes and hash tables, we were able to solve this problem in linear time. Happy coding! 😎
Subscribe to my newsletter
Read articles from Eyuel Dan⭐⭐⭐ directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by