{"id":"6b093ddfbd4755deb67ee0a7","slug":"top-k-frequent","title":"Najczęstsze tagi","summary":"Zliczamy wystąpienia i wybieramy k najpopularniejszych tagów, a remisy rozstrzygamy alfabetycznie. Mapa liczników plus kopiec rozmiaru k albo sortowanie.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["hashing","heap","sorting","counting","bucket-sort"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Returns at most k distinct words: by count (descending), ties alphabetically (ascending). */\nfunction topKFrequent(words: string[], k: number): string[] {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('picks the most frequent words', () => {\n  expect(topKFrequent(['api', 'db', 'api', 'cache', 'db', 'api'], 2)).toEqual(['api', 'db']);\n});\n\ntest('ties are broken alphabetically', () => {\n  expect(topKFrequent(['b', 'a', 'c', 'b', 'a', 'c'], 2)).toEqual(['a', 'b']);\n  expect(topKFrequent(['golang', 'go', 'go', 'golang'], 2)).toEqual(['go', 'golang']);\n});\n\ntest('frequency beats the alphabet', () => {\n  expect(topKFrequent(['zeta', 'zeta', 'alpha'], 1)).toEqual(['zeta']);\n});\n\ntest('k larger than the number of distinct words', () => {\n  expect(topKFrequent(['zeta', 'zeta', 'alpha', 'beta', 'beta'], 10)).toEqual(['beta', 'zeta', 'alpha']);\n});\n\ntest('k = 0 and empty input', () => {\n  expect(topKFrequent(['a', 'b'], 0)).toEqual([]);\n  expect(topKFrequent([], 3)).toEqual([]);\n});\n\ntest('words with digits and hyphens', () => {\n  expect(topKFrequent(['node-20', 'node-18', 'node-20', 'node-18', 'deno'], 3)).toEqual(['node-18', 'node-20', 'deno']);\n});\n\ntest('performance: 252 500 words, 5 000 distinct', () => {\n  const m = 5000;\n  const freq = (j) => ((j * 37) % 100) + 1;\n  const name = (j) => 'tag' + String(j).padStart(4, '0');\n  const words = [];\n  for (let round = 0; round < 100; round++) for (let j = 0; j < m; j++) if (freq(j) > round) words.push(name(j));\n  const expected = [27, 127, 227, 327, 427, 527, 627, 727, 827, 927].map(name);\n  expect(topKFrequent(words, 10)).toEqual(expected);\n  expect(topKFrequent(words, m + 5)).toHaveLength(m);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Returns at most k distinct words: by count (descending), ties alphabetically (ascending).\n * @param {string[]} words\n * @param {number} k\n * @returns {string[]}\n */\nfunction topKFrequent(words, k) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('picks the most frequent words', () => {\n  expect(topKFrequent(['api', 'db', 'api', 'cache', 'db', 'api'], 2)).toEqual(['api', 'db']);\n});\n\ntest('ties are broken alphabetically', () => {\n  expect(topKFrequent(['b', 'a', 'c', 'b', 'a', 'c'], 2)).toEqual(['a', 'b']);\n  expect(topKFrequent(['golang', 'go', 'go', 'golang'], 2)).toEqual(['go', 'golang']);\n});\n\ntest('frequency beats the alphabet', () => {\n  expect(topKFrequent(['zeta', 'zeta', 'alpha'], 1)).toEqual(['zeta']);\n});\n\ntest('k larger than the number of distinct words', () => {\n  expect(topKFrequent(['zeta', 'zeta', 'alpha', 'beta', 'beta'], 10)).toEqual(['beta', 'zeta', 'alpha']);\n});\n\ntest('k = 0 and empty input', () => {\n  expect(topKFrequent(['a', 'b'], 0)).toEqual([]);\n  expect(topKFrequent([], 3)).toEqual([]);\n});\n\ntest('words with digits and hyphens', () => {\n  expect(topKFrequent(['node-20', 'node-18', 'node-20', 'node-18', 'deno'], 3)).toEqual(['node-18', 'node-20', 'deno']);\n});\n\ntest('performance: 252 500 words, 5 000 distinct', () => {\n  const m = 5000;\n  const freq = (j) => ((j * 37) % 100) + 1;\n  const name = (j) => 'tag' + String(j).padStart(4, '0');\n  const words = [];\n  for (let round = 0; round < 100; round++) for (let j = 0; j < m; j++) if (freq(j) > round) words.push(name(j));\n  const expected = [27, 127, 227, 327, 427, 527, 627, 727, 827, 927].map(name);\n  expect(topKFrequent(words, 10)).toEqual(expected);\n  expect(topKFrequent(words, m + 5)).toHaveLength(m);\n});\n"},{"lang":"python","runner":"browser","starter":"def top_k_frequent(words: list[str], k: int) -> list[str]:\n    \"\"\"Returns at most k distinct words: by count (descending), ties alphabetically (ascending).\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def check(words, k, expected):\n    got = top_k_frequent(words, k)\n    assert got == expected, f\"top_k_frequent({words[:8]}, {k}): expected {expected}, got {got}\"\n\n\ndef test_picks_the_most_frequent_words():\n    check([\"api\", \"db\", \"api\", \"cache\", \"db\", \"api\"], 2, [\"api\", \"db\"])\n\n\ndef test_ties_are_broken_alphabetically():\n    check([\"b\", \"a\", \"c\", \"b\", \"a\", \"c\"], 2, [\"a\", \"b\"])\n    check([\"golang\", \"go\", \"go\", \"golang\"], 2, [\"go\", \"golang\"])\n\n\ndef test_frequency_beats_the_alphabet():\n    check([\"zeta\", \"zeta\", \"alpha\"], 1, [\"zeta\"])\n\n\ndef test_k_larger_than_distinct_words():\n    check([\"zeta\", \"zeta\", \"alpha\", \"beta\", \"beta\"], 10, [\"beta\", \"zeta\", \"alpha\"])\n\n\ndef test_k_zero_and_empty_input():\n    check([\"a\", \"b\"], 0, [])\n    check([], 3, [])\n\n\ndef test_words_with_digits_and_hyphens():\n    check([\"node-20\", \"node-18\", \"node-20\", \"node-18\", \"deno\"], 3, [\"node-18\", \"node-20\", \"deno\"])\n\n\ndef test_performance_252k_words():\n    m = 5000\n    freq = [(j * 37) % 100 + 1 for j in range(m)]\n    names = [f\"tag{j:04d}\" for j in range(m)]\n    words = [names[j] for r in range(100) for j in range(m) if freq[j] > r]\n    expected = [names[j] for j in (27, 127, 227, 327, 427, 527, 627, 727, 827, 927)]\n    check(words, 10, expected)\n    got = top_k_frequent(words, m + 5)\n    assert len(got) == m, f\"expected all {m} words, got {len(got)}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\npublic static class Solution\n{\n    /// <summary>Returns at most k distinct words: by count (descending), ties in ordinal order (ascending).</summary>\n    public static List<string> TopKFrequent(string[] words, int k)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"import java.util.*;\n\nclass Solution {\n    /** Returns at most k distinct words: by count (descending), ties alphabetically (ascending). */\n    static List<String> topKFrequent(String[] words, int k) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\n// TopKFrequent returns at most k distinct words: by count (descending), ties alphabetically (ascending).\nfunc TopKFrequent(words []string, k int) []string {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.985Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Blog pokazuje chmurę "},{"type":"text","text":"k","marks":[{"type":"bold"}]},{"type":"text","text":" najpopularniejszych tagów. Mamy listę wszystkich użyć tagów (z powtórzeniami) i trzeba wybrać te, które pojawiają się najczęściej."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Funkcja "},{"type":"text","text":"topKFrequent(words, k)","marks":[{"type":"code"}]},{"type":"text","text":" zwraca listę co najwyżej "},{"type":"text","text":"k","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"różnych","marks":[{"type":"bold"}]},{"type":"text","text":" słów:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"posortowaną malejąco według liczby wystąpień,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"przy równej liczbie wystąpień – rosnąco alfabetycznie (porównanie znak po znaku, jak "},{"type":"text","text":"<","marks":[{"type":"code"}]},{"type":"text","text":" na napisach ASCII; "},{"type":"text","text":"\"go\"","marks":[{"type":"code"}]},{"type":"text","text":" jest przed "},{"type":"text","text":"\"golang\"","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"gdy różnych słów jest mniej niż "},{"type":"text","text":"k","marks":[{"type":"code"}]},{"type":"text","text":", zwracamy wszystkie; dla "},{"type":"text","text":"k = 0","marks":[{"type":"code"}]},{"type":"text","text":" – pustą listę."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Sygnatury: "},{"type":"text","text":"topKFrequent(words, k)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"top_k_frequent(words, k)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.TopKFrequent","marks":[{"type":"code"}]},{"type":"text","text":" (C#), "},{"type":"text","text":"Solution.topKFrequent","marks":[{"type":"code"}]},{"type":"text","text":" (Java), "},{"type":"text","text":"TopKFrequent","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":"words","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"k","marks":[{"type":"code"}]}]}]},{"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":"[\"api\",\"db\",\"api\",\"cache\",\"db\",\"api\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"api\",\"db\"]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"b\",\"a\",\"c\",\"b\",\"a\",\"c\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"a\",\"b\"]","marks":[{"type":"code"}]},{"type":"text","text":" – remis, decyduje alfabet"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"zeta\",\"zeta\",\"alpha\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"5","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"zeta\",\"alpha\"]","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":"3","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":"0 ≤ words.length ≤ 300 000","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"0 ≤ k ≤ 10 000","marks":[{"type":"code"}]},{"type":"text","text":", słowa z małych liter ASCII, cyfr i "},{"type":"text","text":"-","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 + m log k)","marks":[{"type":"bold"}]},{"type":"text","text":" z kopcem rozmiaru "},{"type":"text","text":"k","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"m","marks":[{"type":"code"}]},{"type":"text","text":" – liczba różnych słów) albo "},{"type":"text","text":"O(n + m log m)","marks":[{"type":"bold"}]},{"type":"text","text":" z sortowaniem; pamięć "},{"type":"text","text":"O(m)","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/top-k-frequent-words/","title":"LeetCode 692 – Top K Frequent Words","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:55.987Z","updatedAt":"2026-11-27T08:22:55.987Z"}