2. Valid Anagram
Problem 🔗
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
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.
Solution
Solution in C++ using sort
lf t is an anagram of s (it's the same as saying two strings are permutations), then we know they have the same characters, but in different orders.
Therefore, first we sort the strings and then check if they are equals.
bool checkPermutationstring s, std::string t {
if(s.size() != t.size()) return false;
std::sort(s.begin(), s.end());
std::sort(t.begin(), t.end());
return (s == t);
}
- Time complexity:
(it depends on the sort algorithm) - Space complexity:
Solution in C++ with array
In the first loop we simply count how many times each character appears in s and amount it in an array. Each element in the array rapresents the corresponding value in the alphabet (char_set[0] = 'a', ...).
In the second loop, we do the same for t, but we decrease the value, so if it goes below zero it means the frequency of the characters of the two strings are different.
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
array<int, 26> char_set = {};
for(char c : s)
char_set.at(c - 'a')++;
for(char c : t) {
int index = c - 'a';
char_set.at(index)--;
if(char_set.at(index) < 0)
return false;
}
return true;
}
- Time complexity:
(one pass over s, one pass fort) - Space complexity:
( char_setwill always have 26 elements)