Skip to content

Instantly share code, notes, and snippets.

@msinvent
Last active July 13, 2020 02:07
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/1f3de42ecfa52958bf656a2e27bec6fe to your computer and use it in GitHub Desktop.
Save msinvent/1f3de42ecfa52958bf656a2e27bec6fe to your computer and use it in GitHub Desktop.
All O(1) are not same sample code 1
bool isAnagram(const std::string& str1, const std::string& str2){
// Two string can't be anagram if they are of different size [O(1)]
if(str1.size()!=str2.size()){
return false;
}
// Copy have to be done to sort it later [O(n) space and O(n) time both]
std::string str1Copy = str1;
std::string str2Copy = str2;
// C++ sort implementation [O(nlogn)]
std::sort(str1Copy.begin(), str1Copy.end());
std::sort(str2Copy.begin(), str2Copy.end());
// Final search [O(n)]
return str1Copy==str2Copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment