Skip to content

Commit 3d600b9

Browse files
authored
Improved performance of valid anagram solution
1 parent 61bc960 commit 3d600b9

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

ValidAnagram/solution.cpp

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,21 @@ class Solution {
55
bool isAnagram(string s, string t)
66
{
77
// Use hashmap to keep count of letters in both strings
8-
unordered_map<char, int> s1LetterCount;
9-
unordered_map<char, int> s2LetterCount;
8+
unordered_map<char, int> letterCount;
109

1110
for (auto letter : s)
12-
s1LetterCount[letter]++;
11+
letterCount[letter]++;
1312

1413
for (auto letter : t)
15-
s2LetterCount[letter]++;
14+
letterCount[letter]--;
1615

17-
// The letter counts in each hashmap should match for the strings to be a valid anagram
18-
return (s1LetterCount == s2LetterCount);
16+
// To be a valid anagram the letter counts in the hashmap should be all zeros if the count was the same in both strings
17+
for (const auto& [letter, count]: letterCount)
18+
{
19+
if (count != 0)
20+
return false;
21+
}
22+
23+
return true;
1924
}
2025
};

0 commit comments

Comments
 (0)