0%

242. Valid Anagram

hashmap O(n) time O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int f[256] = {0};
for (char c : s) {
++f[c];
}
for (char c : t) {
if (--f[c] < 0) return false;
}
return true;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool isAnagram(string s, string t) {
if (size(s) != size(t)) return false;
int f[256] = {0};
for (int i = 0; i < size(s); ++i) {
++f[s[i]];
--f[t[i]];
}
return all_of(f, f + 256, [](int x){ return x == 0; });
}
};

Follow up

What if the inputs contain unicode characters? How would you adapt your solution to such case?

Answer

Use a hash table instead of a fixed size counter. Imagine allocating a large size array to fit the entire range of unicode characters, which could go up to more than 1 million. A hash table is a more generic solution and could adapt to any range of characters.