Grokking Oracle Coding Interview
Vote
0% completed
Hidden Document
Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content
.....
.....
.....
Like the course? Get enrolled and start learning!
L
lejafilip
· 2 years ago
vector<vector<string>> groupAnagrams(vector<string>& strs) { std::unordered_map<size_t, std::vector<std::string>> exist; std::vector<std::vector<std::string>> result; for(const auto& str : strs) { std::vector<int> hist(26,0); for(const auto& c : str) { hist[c - 'a']++; } size_t key = 0; for(const auto& c : hist) { key *= 31; key += c; } exist[key].push_back(str); } for(auto& [_, anagrams] : exist) { result.emplace_back(std::move(anagrams)); } return result; }
N
Nicholas Tinsley
· 2 years ago
Sorting the strings takes O(k log(k)), but just doing a pass on each string and counting each character only takes O(k) time. You just allocate an array the size of your character set, and increment the value at that character's index. Finally, you write that array to a string (O(1), as it's determined by the size of your character set), and use that string as the key.
Reading Progress
0%