I am trying to solve a particular leetcode problem but I can't seem to figure out where I am going wrong.
The question is this one:https://leetcode.com/problems/group-anagrams/ and my code is:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& str) {
unordered_map<string, vector<int>> map;
vector<string> newstr = str;
int size = str.size();
//pushing those indices of `str` into the map which share common permutation
for(int i=0; i<size; i++){
sort(newstr[i].begin(), newstr[i].end());
map[newstr[i]].push_back(i);
}
vector<vector<string>> ans;
int i=0;
for(auto itr: map){
int v_size = itr.second.size();
for(int j=0; j<v_size; j++)
//cout<<str[itr.second[j]]<<" "; //this query works perfectly
ans[i].push_back(str[itr.second[j]]); //erroneous code
i++;
}
return vector<vector<string>>();
// return ans;
}
};
Run Code Online (Sandbox Code Playgroud)
You are accessing ans[i]
without allocating any memory in ans
beforehand. This creates a data access that is out of the vector's bounds (0).
If you meant to add a new vector to ans, use ans.push_back()
. As balki said, you can also remove redundant allocations by allocating all entries upon declaration, like this:
vector<vector<string>> ans { map.size() };
Run Code Online (Sandbox Code Playgroud)
This will make your code work without any additional changes needed (as far as I can see).