I am going through Elements of Programming Interview by Aziz, Lee and Prakash one of the questions is how to determine if a string can be permuted to a palindrome. For example edified
can be permuted to deified
and now its a palindrome.
So my first implementation is this:
bool CanFormPalindrome(const string& s) {
std::unordered_map<char, int> letter_count;
for(char c : s) {
letter_count[c]++;
}
int odd_letter_count = 0;
for(std::pair<char, int> letter : letter_count) {
if(letter.second%2 != 0) {
odd_letter_count++;
}
}
return odd_letter_count <= 1;
}
After I passed all the tests I saw the book's cleaner and sleeker implementation (compared to my implementation) which is:
bool CanFormPalindrome(const string& s) { std::unordered_set<char> char_counter; for(char c : s) { if(char_counter.count(c)) { char_counter.erase(c); } else { char_counter.insert(c); } } return char_counter.size() <= 1; }
When I saw the time difference the tester timed my test at around 30 ms and the book's implementation at around 100 ms. I am wondering why my implementation is faster than the book's. My suspicion is that the calls to unordered_set
's count
, erase
, and insert
probably is the main bottle neck as opposed to just insert it just once and increment the value if it exists.
Another question is if you were to ask this on an interview would you care about the space time complexity over speed? Obviously the unordered_set is far more space efficient than the unordered_map, but if its for greater performance gain can we take up more space?