Problem List
This brute force solution works for small inputs but doesn't scale, but I am happy that I've gone from no mediums to a few in just the last couple days. Soon my easy solutions will be fully polished, my mediums will improve, and I'll start working on hards. :)
O(n^2 * k) Check every pair of strings in the worst case, and isAnagram takes O(k) time per comparison.O(n * k)Store the groups and use a map for character counting, which takes up O(n * k) space.func groupAnagrams(strs []string) [][]string {
res := [][]string{{strs[0]}}
if len(strs) == 1 {
return res
}
for i := 1; i < len(strs); i++ {
placed := false
for j := 0; j < len(res); j++ {
if isAnagram(strs[i], res[j][0]) {
placed = true
res[j] = append(res[j], strs[i])
break
}
}
if !placed {
res = append(res, []string{strs[i]})
}
}
return res
}
func isAnagram(a, b string) bool {
if len(a) != len(b) {
return false
}
m := make(map[rune]int)
for _, l := range a {
m[l]++
}
for _, l := range b {
m[l]--
if m[l] < 0 {
return false
}
}
return true
}