Anagram Problem - Grouping all anagrams [reviewed]

 Question

 Given a list of strings, return a list of lists of strings that groups all anagrams.
  Ex. given {trees, bike, cars, steer, arcs}

  return {{cars, arcs}, {bike}, {tree, steer}}

  m = # of words
  n = length of longest word


  Anagrams are the works with same set of letters but in different orders. This means if we can sort individual words, we can easily find out whether two words are the same.

  3:43 min : to think up the solution. But misunderstood the problems
  13:58 min: to code up the solution based on misunderstanding.
  21 secs: to found out the problem during the verification and fix it up.

  First, I overlooked the problem misled by the keyword, anagram. This should not happen.

  Secondly, did not know C++ solution for string sorting, which I know now. std::sort(begin(), end());


Here is the code in C++.
#include<iostream>
#include<string>
#include<map>
#include<list>
#include<algorithm>
using namespace std;
map<string, list<string>>find_anagram_group(string * input, int len)
{
map<string, list<string>> result;
for (int i= 0; i<len; i++)
{
string sorted = input[i];
sort(sorted.begin(), sorted.end());
if (result.find(sorted)!= result.end())
{
result[sorted].push_back(input[i]);
} else {
list<string> l;
l.push_back(input[i]);
result[sorted] = l;
}
}
return result;
}
view raw Anagram.cpp hosted with ❤ by GitHub

End of the code.


UPDATE(2019-07-31): solved the question again in python. Got the code right but did not know how to short chars in the string with python. Had to get an help from ipython console.

-
def compare(prev, next):
if prev < next:
return -1
else:
return 1
def find_groups_of_anagrams(input):
anagram_map = {}
for word in input:
sorted_key = sort_word(word)
if sorted_key not in anagram_map:
anagram_map[sorted_key] = [word]
else:
anagram_map[sorted_key].append(word)
result = []
for k in anagram_map:
result.append(anagram_map[k])
return result
def sort_word(word):
sorted_chars_list = sorted(word, cmp = compare)
return "".join(sorted_chars_list)
anagrams = ['trees', 'bike', 'cars', 'steer', 'arcs']
print("anagrams = {} list of anagrams = {}".format(anagrams, find_groups_of_anagrams(anagrams)))

Practice statistic

09:57: to think of algorithm and write up the code
04:40: to fix the sorting logic.

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the shorted path from the vertex 0 for given list of vertices.