{"id":"6b093ddebd4755deb67ee074","slug":"group-anagrams","title":"Grupowanie anagramów","summary":"Słowa złożone z tych samych liter trafiają do jednej grupy. Ćwiczenie z doboru klucza w mapie – i z kolejności wyników.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["hashing","strings","sorting","hash-map"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Groups anagrams. Groups are ordered by first occurrence; words keep the input order. */\nfunction groupAnagrams(words: string[]): string[][] {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('groups the basic example', () => {\n  expect(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])).toEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]);\n});\n\ntest('empty input', () => {\n  expect(groupAnagrams([])).toEqual([]);\n});\n\ntest('empty strings form one group', () => {\n  expect(groupAnagrams(['', 'a', ''])).toEqual([['', ''], ['a']]);\n});\n\ntest('duplicates stay in the group', () => {\n  expect(groupAnagrams(['ab', 'ba', 'ab'])).toEqual([['ab', 'ba', 'ab']]);\n});\n\ntest('letter counts matter', () => {\n  expect(groupAnagrams(['aab', 'abb', 'bab'])).toEqual([['aab'], ['abb', 'bab']]);\n});\n\ntest('keys that collide in naive signatures', () => {\n  expect(groupAnagrams(['ad', 'bc'])).toEqual([['ad'], ['bc']]);\n  expect(groupAnagrams(['abbbbbbbbbbb', 'aaaaaaaaaaab'])).toEqual([['abbbbbbbbbbb'], ['aaaaaaaaaaab']]);\n});\n\ntest('performance: 52 728 words, 3 276 groups', () => {\n  const words = [];\n  const letter = (i) => String.fromCharCode(97 + i);\n  for (let copy = 0; copy < 3; copy++)\n    for (let x = 0; x < 26; x++)\n      for (let y = 0; y < 26; y++)\n        for (let z = 0; z < 26; z++) words.push(letter(x) + letter(y) + letter(z));\n  const groups = groupAnagrams(words);\n  expect(groups).toHaveLength(3276);\n  expect(groups.reduce((sum, g) => sum + g.length, 0)).toBe(words.length);\n  expect(groups[0]).toEqual(['aaa', 'aaa', 'aaa']);\n  expect(groups[1]).toEqual(['aab', 'aba', 'baa', 'aab', 'aba', 'baa', 'aab', 'aba', 'baa']);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Groups anagrams. Groups are ordered by first occurrence; words keep the input order.\n * @param {string[]} words\n * @returns {string[][]}\n */\nfunction groupAnagrams(words) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('groups the basic example', () => {\n  expect(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])).toEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]);\n});\n\ntest('empty input', () => {\n  expect(groupAnagrams([])).toEqual([]);\n});\n\ntest('empty strings form one group', () => {\n  expect(groupAnagrams(['', 'a', ''])).toEqual([['', ''], ['a']]);\n});\n\ntest('duplicates stay in the group', () => {\n  expect(groupAnagrams(['ab', 'ba', 'ab'])).toEqual([['ab', 'ba', 'ab']]);\n});\n\ntest('letter counts matter', () => {\n  expect(groupAnagrams(['aab', 'abb', 'bab'])).toEqual([['aab'], ['abb', 'bab']]);\n});\n\ntest('keys that collide in naive signatures', () => {\n  expect(groupAnagrams(['ad', 'bc'])).toEqual([['ad'], ['bc']]);\n  expect(groupAnagrams(['abbbbbbbbbbb', 'aaaaaaaaaaab'])).toEqual([['abbbbbbbbbbb'], ['aaaaaaaaaaab']]);\n});\n\ntest('performance: 52 728 words, 3 276 groups', () => {\n  const words = [];\n  const letter = (i) => String.fromCharCode(97 + i);\n  for (let copy = 0; copy < 3; copy++)\n    for (let x = 0; x < 26; x++)\n      for (let y = 0; y < 26; y++)\n        for (let z = 0; z < 26; z++) words.push(letter(x) + letter(y) + letter(z));\n  const groups = groupAnagrams(words);\n  expect(groups).toHaveLength(3276);\n  expect(groups.reduce((sum, g) => sum + g.length, 0)).toBe(words.length);\n  expect(groups[0]).toEqual(['aaa', 'aaa', 'aaa']);\n  expect(groups[1]).toEqual(['aab', 'aba', 'baa', 'aab', 'aba', 'baa', 'aab', 'aba', 'baa']);\n});\n"},{"lang":"python","runner":"browser","starter":"def group_anagrams(words: list[str]) -> list[list[str]]:\n    \"\"\"Groups anagrams. Groups are ordered by first occurrence; words keep the input order.\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def check(words, expected):\n    got = group_anagrams(words)\n    assert got == expected, f\"group_anagrams({words}): expected {expected}, got {got}\"\n\n\ndef test_basic_example():\n    check([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"], [[\"eat\", \"tea\", \"ate\"], [\"tan\", \"nat\"], [\"bat\"]])\n\n\ndef test_empty_input():\n    check([], [])\n\n\ndef test_empty_strings_form_one_group():\n    check([\"\", \"a\", \"\"], [[\"\", \"\"], [\"a\"]])\n\n\ndef test_duplicates_stay():\n    check([\"ab\", \"ba\", \"ab\"], [[\"ab\", \"ba\", \"ab\"]])\n\n\ndef test_letter_counts_matter():\n    check([\"aab\", \"abb\", \"bab\"], [[\"aab\"], [\"abb\", \"bab\"]])\n\n\ndef test_keys_that_collide_in_naive_signatures():\n    check([\"ad\", \"bc\"], [[\"ad\"], [\"bc\"]])\n    check([\"abbbbbbbbbbb\", \"aaaaaaaaaaab\"], [[\"abbbbbbbbbbb\"], [\"aaaaaaaaaaab\"]])\n\n\ndef test_performance_52k_words():\n    letters = \"abcdefghijklmnopqrstuvwxyz\"\n    words = [x + y + z for _ in range(3) for x in letters for y in letters for z in letters]\n    groups = group_anagrams(words)\n    assert len(groups) == 3276, f\"expected 3276 groups, got {len(groups)}\"\n    assert sum(len(g) for g in groups) == len(words), \"every word must be in exactly one group\"\n    assert groups[0] == [\"aaa\"] * 3, f\"first group: {groups[0]}\"\n    assert groups[1] == [\"aab\", \"aba\", \"baa\"] * 3, f\"second group: {groups[1]}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\npublic static class Solution\n{\n    /// <summary>Groups anagrams. Groups are ordered by first occurrence; words keep the input order.</summary>\n    public static List<List<string>> GroupAnagrams(string[] words)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"import java.util.*;\n\nclass Solution {\n    /** Groups anagrams. Groups are ordered by first occurrence; words keep the input order. */\n    static List<List<String>> groupAnagrams(String[] words) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\n// GroupAnagrams groups anagrams. Groups are ordered by first occurrence; words keep the input order.\nfunc GroupAnagrams(words []string) [][]string {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.291Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Wyszukiwarka tagów chce podpowiadać literówki typu „przestawione litery”. Pierwszy krok: pogrupować słowa w "},{"type":"text","text":"anagramy","marks":[{"type":"bold"}]},{"type":"text","text":", czyli słowa złożone z dokładnie tych samych liter w tej samej liczbie ("},{"type":"text","text":"\"listen\"","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"\"silent\"","marks":[{"type":"code"}]},{"type":"text","text":")."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Funkcja dostaje listę słów i zwraca listę grup:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"grupy są ułożone według "},{"type":"text","text":"pierwszego wystąpienia","marks":[{"type":"bold"}]},{"type":"text","text":" dowolnego ich słowa na wejściu,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"w grupie słowa zachowują "},{"type":"text","text":"kolejność z wejścia","marks":[{"type":"bold"}]},{"type":"text","text":", duplikaty zostają,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"pusty napis też jest słowem (wszystkie puste napisy są swoimi anagramami)."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Sygnatury: "},{"type":"text","text":"groupAnagrams(words)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"group_anagrams(words)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.GroupAnagrams","marks":[{"type":"code"}]},{"type":"text","text":" (C#), "},{"type":"text","text":"Solution.groupAnagrams","marks":[{"type":"code"}]},{"type":"text","text":" (Java), "},{"type":"text","text":"GroupAnagrams","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"heading","attrs":{"level":2,"id":"przyklady"},"content":[{"type":"text","text":"Przykłady"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wejście"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wynik"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[\"eat\", \"tea\", \"ate\"], [\"tan\", \"nat\"], [\"bat\"]]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"aab\", \"abb\", \"bab\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[\"aab\"], [\"abb\", \"bab\"]]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"ad\", \"bc\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[\"ad\"], [\"bc\"]]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Do 60 000 słów, każde o długości 0–20, tylko małe litery "},{"type":"text","text":"a–z","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Czas "},{"type":"text","text":"O(n · k log k)","marks":[{"type":"bold"}]},{"type":"text","text":" przy kluczu z posortowanych liter albo "},{"type":"text","text":"O(n · k)","marks":[{"type":"bold"}]},{"type":"text","text":" przy kluczu z liczników liter ("},{"type":"text","text":"k","marks":[{"type":"code"}]},{"type":"text","text":" – długość słowa), pamięć "},{"type":"text","text":"O(n · k)","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/group-anagrams/","title":"LeetCode 49 – Group Anagrams","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:54.292Z","updatedAt":"2026-11-27T08:22:54.292Z"}