Skip to content

Commit

Permalink
ADD: Group anagram - medium problem
Browse files Browse the repository at this point in the history
  • Loading branch information
InclinedScorpio committed Sep 1, 2024
1 parent c2bb0b4 commit 2342f05
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions XDaysChallenge/90DaysChallenge/Day1 - hashing/group_anagrams.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// https://leetcode.com/problems/group-anagrams/

/**
* Should now hashing and how to use it to reduce O(N^2) complexity
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {

unordered_map<string, vector<string>> store;

vector<string> copyStrs = strs;

// sort all of them
for(int i=0;i<strs.size();i++) {
sort(strs[i].begin(), strs[i].end());
}

vector<bool> itemPicked(strs.size(), false);
// now compare
vector<vector<string>> result;

for(int i=0;i<strs.size();i++) {
store[strs[i]].push_back(copyStrs[i]);
}
for(auto i = store.begin();i!=store.end();i++) {
result.push_back(i->second);
}
return result;
}
};

0 comments on commit 2342f05

Please sign in to comment.