Problem List

Group Anagrams

May 30, 2025Go hash table, string, sorting, arraymedium

Problem

Approach

Edge Cases

Reflections

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. :)

Performance

Complexity

Go Solution
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
}
LeetCode Problem Link