Skip to content

Instantly share code, notes, and snippets.

@msinvent
Last active July 13, 2020 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msinvent/83a8056bacbd384a055696b8e6482ec7 to your computer and use it in GitHub Desktop.
Save msinvent/83a8056bacbd384a055696b8e6482ec7 to your computer and use it in GitHub Desktop.
isAnagram function description
bool isAnagram(const std::string& str1, const std::string& str2)
{
if(str1.size() != str2.size()){
return false;
}
std::unordered_map<char,uint32_t> mapStr1;
std::unordered_map<char,uint32_t> mapStr2;
constexpr uint16_t maxSizeOfMap = 1<<(sizeof(char)*8);
mapStr1.reserve(maxSizeOfMap);
mapStr2.reserve(maxSizeOfMap);
// Loop through string and create frequency map of characters
// [O(n) average time complexity, O(1) space complexity, because the number of charactes types is fixed]
for(auto it: str1){
mapStr1[it]++;
}
for(auto it: str2){
mapStr2[it]++;
}
// Final search [O(n)]
return mapStr1 == mapStr2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment