I was solving Group Anagram problem in leetcode. Link for the problem https://leetcode.com/problems/group-anagrams/
Below is the code which I wrote
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& inp) {
if(inp.size() == 0)
return vector<vector<string> > {{}};
int count = 1;
map<char, long long> alphaVal;
for (char i = 'a'; i <= 'z'; i++) {
alphaVal[i] = int(rand());
}
map<long long, vector<string> > prep;
for (auto value : inp) {
long long temp = 0;
for (auto c_p : value) {
temp += alphaVal[c_p];
}
//cout << "temp " << temp << endl;
prep[temp].push_back(value);
}
vector < vector<string> > ans;
for (auto it = prep.begin(); it != prep.end(); it++) {
vector<string> temp;
for (int i = 0; i < it->second.size(); i++) {
//cout << it->second[i] << " ";
temp.push_back(it->second[i]);
}
ans.push_back(temp);
}
return ans;
}
};
I have two questions:
Even though the above solution worked, is using random is a really good idea?
Previously I wrote a logic to check the characters and store the string.
map<set<char>, vector<string> > prep; for (auto value : inp) { set<char> temp; for (auto c_p : value) { temp.insert(c_p); } prep[temp].push_back(value); }
For the above logic one test case failed
ip: ["ddddddddddg","dgggggggggg"]
op: [["ddddddddddg","dgggggggggg"]]
Even though the two strings are unique, the set hash calculation says it is same. Any idea why this behavior on the selected test case? Was just curious to know. Thanks for the answers!
"ddddddddddg"
are {d, g}, same as in"dgggggggggg"
(orggd
).) \$\endgroup\$random
is inis using random is a really good idea?
- did you forget to present something? \$\endgroup\$