Beyond Big O

Anagram groups

Anagram groups

Medium

Your task

Put words with the same letter counts into the same group.

Required API

  • GroupAnagrams
    func GroupAnagrams(words []string) [][]string

Behavior

  • Keep words in their original input order within each group, including duplicates.
  • Order the groups by the first input word belonging to each group.
  • Empty strings form a group too.

Constraints

  • The input is valid: 0–100 words, each containing 0–40 lowercase ASCII letters a–z.
  • Return an empty list for empty input.
  • Leave the input unchanged and keep separate calls independent.
  • Use only the standard library.
  • Aim for O(total characters + number of words) time with character-count keys.
Notes and example notation

Examples use {"words": [...]}.

Examples

The runner calls your functions directly; you do not need to parse JSON.

Example 1 · empty

Arguments
words
[]
Expected return
[]
Test data
Input
{"words":[]}
Expected output
[]

Example 2 · first seen order

Arguments
words
[
  "tea",
  "tan",
  "eat",
  "ate",
  "nat",
  "bat"
]
Expected return
[
  [
    "tea",
    "eat",
    "ate"
  ],
  [
    "tan",
    "nat"
  ],
  [
    "bat"
  ]
]
Test data
Input
{"words":["tea","tan","eat","ate","nat","bat"]}
Expected output
[["tea","eat","ate"],["tan","nat"],["bat"]]

Example 3 · letter counts

Arguments
words
[
  "ab",
  "aab",
  "ba",
  "aba"
]
Expected return
[
  [
    "ab",
    "ba"
  ],
  [
    "aab",
    "aba"
  ]
]
Test data
Input
{"words":["ab","aab","ba","aba"]}
Expected output
[["ab","ba"],["aab","aba"]]

Example 4 · empty and duplicates

Arguments
words
[
  "",
  "a",
  "",
  "a"
]
Expected return
[
  [
    "",
    ""
  ],
  [
    "a",
    "a"
  ]
]
Test data
Input
{"words":["","a","","a"]}
Expected output
[["",""],["a","a"]]
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…